码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-07-18 21:39:14      阅读:477      评论:0      收藏:0      [点我收藏+]

标签:lin   color   adt   style   imp   excel   os.walk   os模块   .sh   

 

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

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

标签:lin   color   adt   style   imp   excel   os.walk   os模块   .sh   

原文地址:https://www.cnblogs.com/yahengwang/p/9332570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!