Somewhat new to Python but this is a question about writing functions without repeating oneself.
Using openpyxl
I've created a document class and a workbook ( wb
) with 3 sheets inside:
self.sheet1 = self.wb['sheet1']
self.sheet2 = self.wb['sheet2']
self.sheet3 = self.wb['sheet3']
I also have a function in this class that looks through rows of sheet3
for particular text.
def find_text_row_number(self, text):
text_row_number = set([])
for row in self.sheet3.iter_rows(self.sheet3.min_row,self.sheet3.max_row):
for cell in row:
if cell.value == text:
text_row_number.add(cell.row)
return sorted(text_row_number)
My question is: How can I call this function elsewhere in the program and have it search sheet2
, instead of sheet3
? Have tried looking into decorators and also using a default value ( sheet=self.sheet3
), but this raises an error because self
has not yet been defined.
Is there maybe a more efficient way to write this particular function? Or some aspect of Python I'm missing that could help out here?
Try:
def find_text_row_number(self, text, sheet_name='sheet1'):
text_row_number = set([])
sheet = getattr(self, sheet_name)
for row in sheet.iter_rows(sheet.min_row, sheet.max_row):
for cell in row:
if cell.value == text:
text_row_number.add(cell.row)
return sorted(text_row_number)
Don't use separate variables, put all the sheets in a list. Then you can access the one you want with an index.
The first code would initialize the list:
self.sheets = [self.wb['sheet1'], self.wb['sheet2'], self.wb['sheet3']]
Then your other method can take an optional index.
def find_text_row_number(self, text, sheet_num = 3):
sheet = self.sheets[sheet_num-1]
text_row_number = set([])
for row in sheet.iter_rows(sheet.min_row,sheet.max_row):
for cell in row:
if cell.value == text:
text_row_number.add(cell.row)
return sorted(text_row_number)
When you want to process sheet2
, use
x.find_text_row_number("text", sheet_num = 2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.