使用python內建模組os和openpyxl搜尋指定檔案夾下Excel中的內容

來源:互聯網
上載者:User

標籤:lin   color   adt   style   imp   excel   os.walk   os模組   .sh   

 

      在指定路徑下,搜尋Excel檔案中包含的指定內容,首先需要遍曆指定路徑,得到該路徑下所有Excel檔案的絕對/相對路徑;然後讀取Excel中內容,將檔案中的每個儲存格的值與要搜尋的內容進行判斷(正則比較,等值比較)。因此,實現該功能需要完成兩部分內容,路徑遍曆Excel檔案內容讀取

使用os模組遍曆指定路徑下的所有excel檔案
import osdef 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 openpyxldef 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

使用python內建模組os和openpyxl搜尋指定檔案夾下Excel中的內容

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.