使用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