使用python内置模块os和openpyxl搜索指定文件夹下Excel中的内容


 

      在指定路径下,搜索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))

 

参考资料

openpyxl

os


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM