Python:使用 win32 打开 Excel 文件

问题描述 投票:0回答:3

我的代码昨天可以工作,但是今天当我尝试再次运行它时,它给了我一个错误,我试图解决这个问题,但我做不到。希望你能在这里帮助我。非常感谢!

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, '发生异常。', (0, 'Microsoft Excel', “抱歉,我们找不到 ZPC.xlsx。是否有可能它已被移动、重命名或删除?”, 'xlmain11.chm ', 0, -2146827284), 无)

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

python excel win32com
3个回答
1
投票

您可以尝试打印您的

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)

另外,如果您希望有更优雅的加入方式

dirpath
file

您可以使用

os.path.join(dirpath, file)

0
投票

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

使用 wb = excel.Workbooks.Open(dirpath + file) 之前的“excel.Visible = True”。


0
投票

我遇到了同样的问题,并按照链接中定义的步骤进行工作 https://stackoverflow.com/a/76919456/12395911

© www.soinside.com 2019 - 2024. All rights reserved.