Searching Excel File For String Using Openpyxl - (Python 3.10)
I'm searching for a string, in column A, within four worksheets. The script works if the cell value is found within the worksheet.
I want to know how to determine if the cell doesn't exist? (so I can the search for using an alternative string).
Script (I've attached a photo of the results)
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
import colorama
from colorama import init
init()
from colorama import Fore, Style, Back
import os
import shutil
import math
from decimal import Decimal
from openpyxl.styles import Alignment
from inspect import currentframe
import time
########################################
#########################################
src_path ="/Users/data/"
xlfileName = "test.xlsx"
xlfile = src_path + xlfileName
wb = Workbook()
wb = load_workbook(xlfile)
#########################################
#########################################
def get_linenumber():
cf = currentframe()
return cf.f_back.f_lineno
#########################################
#########################################
#########################################
#########################################
for xws in wb.sheetnames:
worksheet = wb[xws]
print(Style.RESET_ALL)
print(Fore.BLUE, "Looping Through Worksheet Name -- ", worksheet, "Script line is -- ", get_linenumber())
print(Style.RESET_ALL)
for cell in worksheet['A']:
search_string33 = "Current debt" #
search_string34 = "test" #
try:
if search_string33 == cell.value:
offset_colB_CD = cell.offset(row=0, column=1)
print(Fore.RED, ( "Line 52 -- worksheet -- ", worksheet, "Searching for --", search_string33, "isinstance --", isinstance(search_string33, type(None))))
if(offset_colB_CD.coordinate is None):
print("Line 54 -- null value detected in -- ", worksheet)
elif(offset_colB_CD.coordinate is not None):
print(Fore.LIGHTRED_EX, "Line 56 -- worksheet -- ", worksheet," -- cell cordinate found --", offset_colB_CD.coordinate, " -- cell value found --", offset_colB_CD.value )
print(Style.RESET_ALL)
else:
print("Line 59 if statement passed by on else")
time.sleep(5)
except (AttributeError, TypeError):
continue

