我的代码是
#Opens template for creating final report
excel = win32.dynamic.Dispatch('Excel.Application')
template = os.path.abspath((folderpath+'\Poop.xlsx'))
wb = excel.Workbooks.Open(template)
freshws= wb.Sheets("Fresh") #Sheet names must match perfectly
secws= wb.Sheets("sec")
cur.execute("Select * from FIRALL")
freshdata=list(cur.fetchall())
#writes to the first sheet
datarowlen=0
for i,a in enumerate(freshdata):
datarowlen = len(a)
for j,b in enumerate(a):
freshws.Cells(i+1,j+1).Value = a[j]
cur.execute("Select * from SECVE")
secdata=list(cur.fetchall())
#writes to the second sheet
datarowlen=0
for i,a in enumerate(secdata):
datarowlen = len(a)
for j,b in enumerate(a):
secws.Cells(i+1,j+1).Value = a[j]
#saves the report
wb.SaveAs()
wb.Close()
运行代码时出现的错误是
Traceback (most recent call last):
File "main.py", line 369, in <module>
wb = excel.Workbooks.Open(template)
File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel'
, "Microsoft Excel cannot access the file 'path to stuff------------------------
Poop Report\\Poop.xlsx'. There are several possible reasons:\n\n\u2022 The file
name or path does not exist.\n\u2022 The file is being used by another program.\
n\u2022 The workbook you are trying to save has the same name as a currently ope
n workbook.", 'xlmain11.chm', 0, -2146827284), None)
我收到一个弹出对话框,显示访问被拒绝。该文件不是只读的,并且我是要打开的工作簿的所有者。我已经尝试过
win32.gencache.EnsureDispatch('Excel.Application')
我仍然得到同样的错误。我有什么遗漏的吗?我尝试使用动态思维来解决此错误,但是未成功。
另一个错误是在我尝试修复此代码时出现了Pywins -2147418111错误。
folderpath
变量是从哪里来的?因为看起来你正在将路径'path to stuff------------------------ Poop Report\\Poop.xlsx'
传递给 Excel,这显然不是一个有效的路径,这就是为什么你会得到那个错误的原因。 - abarnert