Python: 用 win32 打开 Excel 文件

Python: Open Excel file with win32

我的代码昨天运行正常,但今天当我再次尝试 运行 时,它抛出了一个错误,我试图解决这个问题,但我做不到。希望你能帮我解决这个问题。非常感谢!

import fnmatch
import os
import scipy as s
import pandas as pd
import win32com.client as win32 

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.xlsx'):
    print(file)
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(file)
    excel.Visible = False
    excel.DisplayAlerts = False
    wb.DoNotPromptForConvert = True
    wb.CheckCompatibility = False

    ws = wb.Worksheets('Exec Summary')
    ws.Activate
    canvas = ws.Shapes

    for shp in canvas:
        if shp.TextFrame.Characters:
            print("Comments Found")
            print(shp.TextFrame2.TextRange)
            break
            wb.Close(True)

这是系统抛出的错误:

---> 11 wb = excel.Workbooks.Open(文件)

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find ZPC.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

我已经检查并确认该文件已经在目录中。你们以前遇到过这个吗?

你能试着打印你的 file 看看会发生什么吗?

这里可能发生的情况是您没有在 os.listdir('.') 中正确指示目录路径。
os.listdir('.') 将检查您 运行 所在的 python 脚本所在的默认目录。
如果是同一个文件夹,就可以了。
但如果不是,则必须特别包括文件夹的确切路径。您的确切文件路径应该是什么样子的示例:

filepath = r'C:\Users\yournamehere\Desktop\yourfolderhere\' + 'ZPC.xlsx'  

您的 os.listdir 的示例:

dirpath = r'C:\Users\yournamehere\Desktop\yourfolderhere\'  
for file in os.listdir(dirpath):  
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(dirpath + file)

此外,如果您希望以更优雅的方式加入 dirpathfile
您可以使用

os.path.join(dirpath, file)

我知道回答这个问题可能为时已晚,但请尝试使用

"excel.Visible = True" 在使用 wb = excel.Workbooks.Open(dirpath + file).

之前