为什么我的Python代码无法“另存为”Excel文件?

7 投票
1 回答
25241 浏览
提问于 2025-04-16 04:15

我有一个 Python 的 ExcelDocument 类,它提供了一些方便的方法来读取、写入和格式化 Excel 文件。但是在一些看起来很简单的 Python 代码中,我遇到了一个奇怪的错误。我有一个保存方法和一个 saveAs 方法:

def save(self):
   ''' Save the file '''
   self.workbook.Save()

def saveAs(self, newFileName):
   ''' Save the file as a new file with a different name '''
   self.workbook.SaveAs(newFileName)

保存方法运行得很好,但当我尝试调用 saveAs 方法 - myExcelObject.saveAs("C:/test.xlsx") - 时,我收到了以下错误:

Traceback (most recent call last):
  File "C:\workspace\Utilities\src\util\excel.py", line 201, in <module>
    excel.saveAs("C:/test.xlx")
  File "C:\workspace\Utilities\src\util\excel.py", line 185, in saveAs
    self.workbook.SaveAs(newFileName)
  File "<COMObject Open>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"Microsoft Office Excel cannot access the file 'C:\\//8CBD2000'. 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 open workbook.", u'C:\\Program Files\\Microsoft Office\\Office12\\1033\\XLMAIN11.CHM', 0, -2146827284), None)

有人能解释一下发生了什么吗?

1 个回答

19

我发现(这是我亲身经历的)SaveAs 不支持斜杠 /
你可以试试 saveAs("C:\\test.xlx") 这样的写法。

撰写回答