【问题标题】:excel access denied with win32 python pywin32excel访问被win32拒绝 python pywin32
【发布时间】:2013-06-15 04:23:49
【问题描述】:

我的代码是

#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 变量来自哪里?因为看起来您正在向 Excel 传递路径 'path to stuff------------------------ Poop Report\\Poop.xlsx',这显然不是有效路径,这正是您收到该错误的原因。
  • 我只是把它放在那里以隐藏路径,路径不是问题,因为我使用 openpyxt 没有问题,但是它无法处理数据透视表或更新它们。

标签: python excel winapi pywin32 win32com


【解决方案1】:

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

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

这确实解决了一个完全相同的问题。

【讨论】:

  • 我不敢相信就是这样。谢谢你,谢谢你,马修。我现在不知道该笑还是该哭。
  • 这行得通,但为什么呢?为什么 TF Windows 会有这么随机的 bug?这些目录将如何发挥作用?你是怎么想到的?
【解决方案2】:

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

我打开工作簿所做的主要更改是路径中从 / 到 \ 的斜线。

然后我无法选择工作表名称,直到我让 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

希望这可以帮助遇到与我相同的问题的其他人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多