python操作Excel

工作需要,列出目录下所有Excel的所有Sheet的名字。
目录中有一部分xls文件,一部分xlsx文件。
openpyxl不支持读取xls文件,需要先转换成xlsx文件,再操作。

from openpyxl import  load_workbook
import os
import  fnmatch
import win32com.client

for root, dirs, files in os.walk('D:\\test\\blackList\\blackList'):
    xlsfiles = fnmatch.filter(files, "*.xls")
    for filename in xlsfiles:
        filePath = os.path.join(root, filename)
        excel = win32com.client.gencache.EnsureDispatch('Excel.Application') 
        wb = excel.Workbooks.Open(filePath)
        wb.SaveAs(filePath + 'x', FileFormat=51)
        wb.Close()
        excel.Application.Quit()

for root, dirs, files in os.walk('D:\\test\\blackList\\blackList'):
    xlsfiles = fnmatch.filter(files, "*.xlsx")
    for filename in xlsfiles:
        filePath = os.path.join(root, filename)
        wb = load_workbook(filePath)
        sts = wb.sheetnames
        print(filePath,sts)
        wb.close()

你可能感兴趣的:(开发)