excel访问被win32 python pywin32拒绝

我的代码是

#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) 

我得到一个popup式对话框,表示访问被拒绝。 该文件不是只读的,我是试图打开的工作簿的所有者。 我试过了

 win32.gencache.EnsureDispatch('Excel.Application') 

我仍然得到同样的错误。 有什么我失踪? 我改用dynamic思维,后期绑定可以解决这个错误。

另一个错误,我曾经是Pywins -2147418111错误,当我试图解决这个代码。

一位同事和我正在诊断这个确切的问题。 我不能相信这是多么模糊,我们通过search与.NET等效代码相似的问题find了解决scheme:

要修复,请在64位体系结构的“C:\ Windows \ SysWOW64 \ config \ systemprofile \”或32位服务器上的“C:\ Windows \ System32 \ config \ systemprofile \”中创build一个名为“Desktop”的文件夹。

这真正解决了一个完全相同的问题。

如果有人可以评论为什么我会欣赏这个,我最终修复了这个问题。

我改变打开工作簿的主要事情是在path中的斜线

然后,我无法select表单名称,直到我使excel可见。

 excel.Visible = True wb = excel.Workbooks.Open((excelreport+"\Poop.xlsx")) 

奇怪的是,摆脱了pywins错误

也改变了如何填补它现在

 cur.execute("Select * from FIRALL") freshdata=list(cur.fetchall()) #writes to the first sheet freshws.Range(freshws.Cells(2,1),freshws.Cells((len(freshdata)+1),len(freshdata[0]))).Value = freshdata 

希望这有助于其他遇到同样问题的人员。