在指定路徑下,搜索Excel文件中包含的指定內容,首先需要遍歷指定路徑,得到該路徑下所有Excel文件的絕對/相對路徑;然后讀取Excel中內容,將文件中的每個單元格的值與要搜索的內容進行判斷(正則比較,等值比較)。因此,實現該功能需要完成兩部分內容,路徑遍歷和Excel文件內容讀取。
使用os模塊遍歷指定路徑下的所有excel文件
import os def files(dirpath, suffix=['.xls', 'xlsx']): for root , dirs, files in os.walk(dirpath): for name in files: if os.path.splitext(name)[-1] in suffix: yield os.path.join(root, name)
使用openpyxl讀取excel文件內容
import openpyxl def econtent(fh, query): wb = openpyxl.load_workbook(fh) sheets = wb.sheetnames for name in sheets: sheet = wb[name] for r in range(1, sheet.max_row+1): for c in range(1, sheet.max_column+1): v = sheet.cell(row=r, column=c) if v == query: print("在{}文件的表{}中找到字符串{}".format(fh, name, query))