当前我尝试保存XLSM文件时如下:
from win32com.client import Dispatch
# Open Excel workbook
xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Add(r"C:\Users\ryan\Desktop\Book1.xlsm")
# Make some changes
# blah blah blah
# Save the workbook in XLSM format with new name
wb.SaveAs(r"C:\Users\ryan\Desktop\Book1 - XLSM.xlsm")
xl.Quit()
我收到以下错误......
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<COMObject Add>", line 7, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel'
, 'This extension can not be used with the selected file type. Change the file e
xtension in the File name text box or select a different file type by changing t
he Save as type.', 'xlmain11.chm', 0, -2146827284), None)
如何以新文件格式保存?
注意 - 当尝试将已经是XLSM的文件保存为XLSM时,会导致相同的错误。
答案 0 :(得分:2)
文件的格式由您在致电SaveAs
时指定的FileFormat
参数确定。由于未指定值,因此选择默认值.xlsx。 documentation列出了可能的值。您需要使用xlOpenXMLWorkbookMacroEnabled
。
代码如下:
xlOpenXMLWorkbookMacroEnabled = 52
....
wb.SaveAs(filename, FileFormat=xlOpenXMLWorkbookMacroEnabled)