import os import xlrd import xlwt def w2p_add(files_root): files_root = files_root.replace('\\', '\\\\') return files_root def search(kw, file, sheet): # 打开xls文档 r = 0 for root, dir, file in os.walk(file): for f in file: add = os.path.join(root, f) endswith=(".xls","xlsx") if f.endswith(endswith): try: rdbook = xlrd.open_workbook(add) names = rdbook.sheet_names() # 打开xls中的工作表,并查找单元格的值 for i in names: ws = rdbook.sheet_by_name(i) # 获取工作表 for row in range(ws.nrows): value = ws.row_values(row) # 生成每一行的值 列表 for j in value: if kw in str(j): print(add,"found") sheet.write(r, 0, add) sheet.write(r, 1, i) sheet.write(r, 3, j) sheet.write(r, 2, row) sheet.write(r, 4, root.split("\\")[-2]) sheet.write(r, 5, root.split("\\")[-1]) #sheet.write(r, 6, root.split(".")[-2]) r += 1 break except xlrd.biffh.XLRDError: continue file = input(("要锁定查找的目录:")) w2p_add(file) keyword = input("需要查找的值是:") # 查找的目标文件夹。 wtbook = xlwt.Workbook() wtsheet = wtbook.add_sheet('result') search(keyword, file, wtsheet) wtbook.save(f"{keyword}_found.xls")
python | 查找excel文档中指定关键字的代码