为什么我不能从Python代码中“另存为”Excel文件?

时间:2010-09-16 20:14:06

标签: python save-as

我有一个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 个答案:

答案 0 :(得分:14)

我发现{很难)SaveAs不支持斜杠/。 请改为saveAs("C:\\test.xlx")