使用pywin32查找Excel工作簿
我下载并安装了pywin32这个库。我想用pywin32打开一个工作簿,我几乎可以肯定我写的代码是对的,但我遇到了这样的错误。
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"'Kithenshiftweekly.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.", u'xlmain11.chm', 0, -2146827284), None)
我现在的代码是这样的(不多)
import win32com.client
x1 = win32com.client.Dispatch("Excel.Application")
x1.Visible = True
x1.Workbooks.Open("Kitchen")
x1.Workbooks.Open("Kitchen") 这行代码出现了问题。
但是它找不到这个工作簿。到底发生了什么呢?
1 个回答
1
这里有两个问题;首先,你需要加上文件的扩展名(比如 "Kitchen.xlsx"),其次,你还得提供工作簿的完整路径。所以如果你的工作簿是 "Kitchen.xlsx",而你的脚本在同一个文件夹里,那么你的代码应该像这样:
import win32com.client
import os
x1 = win32com.client.Dispatch("Excel.Application")
x1.Visible = True
x1.Workbooks.Open(os.path.join(os.getcwd(), "Kitchen.xlsx"))
(os.getcwd() 这个函数会返回你脚本所在文件夹的完整路径。如果你想把代码和工作簿放在不同的文件夹里,你可以通过字符串来指定路径。你可以打印 os.getcwd() 来看看怎么做。)