gpt4 book ai didi

python - pywintypes.com_使用 Python 打开 Excel 时出错

转载 作者:行者123 更新时间:2023-11-30 22:53:24 29 4
gpt4 key购买 nike

我有以下脚本,是从这里模仿的(http://pythonexcels.com/python-excel-mini-cookbook/):

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('words.xlsx')

它返回以下错误(完整回溯)

Traceback (most recent call last): File "", line 1, in wb = excel.Workbooks.Open('words.xlsx') File "C:directory\Python35\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7\Workbooks.py", line 78, in Open , Converter, AddToMru, Local, CorruptLoad) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "'words.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", 'xlmain11.chm', 0, -2146827284), None)

当我选择使用 openpyxl 的函数打开工作簿时,没有问题(引用此 https://automatetheboringstuff.com/chapter12/ )。 python文件和excel文件位于同一文件夹中。我是否调用了不恰当的内容?

我确信该文件拼写正确(words.xlsx)并且它与 python 文件位于同一文件夹中。

如有任何想法,我们将不胜感激。

最佳答案

试试这个:

import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
path = os.getcwd().replace('\'','\\') + '\\'
wb = excel.Workbooks.Open(path+'words.xlsx')

异常(exception)的是路径错误,而不是模块系统错误。

'xlmain11.chm' 是空的,所以不需要这个。

路径字符串上使用转义字符时要小心。脚本和工作文件在同一目录中!

希望有帮助

关于python - pywintypes.com_使用 Python 打开 Excel 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211088/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com