excel访问被win32 python pywin32拒绝

Drf*_*ink 1 python excel winapi pywin32 win32com

我的代码是

#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()
Run Code Online (Sandbox Code Playgroud)

我运行代码时遇到的错误是

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)
Run Code Online (Sandbox Code Playgroud)

我得到一个弹出对话框,提示访问被拒绝。该文件不是只读文件,我是其尝试打开的工作簿的所有者。我试过了

win32.gencache.EnsureDispatch('Excel.Application')
Run Code Online (Sandbox Code Playgroud)

我仍然遇到相同的错误。有什么我想念的吗?我转向动态思维,认为后期绑定可以解决此错误。

当我尝试修复此代码时,我遇到的另一个错误是Pywins -2147418111错误。

Mat*_*ord 6

我和一位同事正在诊断这个确切的问题。我简直不敢相信这是多么的晦涩,我们通过使用.NET等效代码搜索相似的问题找到了解决方案:

要解决此问题,请在64位体系结构的“ C:\ Windows \ SysWOW64 \ config \ systemprofile \”中创建一个名为“ Desktop”的文件夹,在32位服务器的“ C:\ Windows \ System32 \ config \ systemprofile \”中创建一个名为“ Desktop”的文件夹。

这确实解决了一个绝对相同的问题。

  • 我简直不敢相信。谢谢您,谢谢Matthew。我现在不知道该笑还是哭。 (2认同)

Drf*_*ink 5

由于某种原因我最终修复了它,如果有人能评论为什么我会感激这一点。

我打开工作簿时更改的主要内容是路径中从 / 到 \ 的斜杠。

然后我无法选择工作表名称,直到我使 Excel 可见。

excel.Visible = True
wb = excel.Workbooks.Open((excelreport+"\Poop.xlsx"))
Run Code Online (Sandbox Code Playgroud)

奇怪的是,它消除了 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
Run Code Online (Sandbox Code Playgroud)

希望这对遇到与我相同问题的其他人有所帮助。