当我当前尝试保存XLSM文件时:
from win32com.client import Dispatch
# Open Excel workbook
xl = Dispatch("Excel.Application")
wb = xl.Workbooks.Add(r"C:UsersryanDesktopBook1.xlsm")
# Make some changes
# blah blah blah
# Save the workbook in XLSM format with new name
wb.SaveAs(r"C:UsersryanDesktopBook1 - 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。
文件的格式由您在调用SaveAs
时指定的FileFormat
参数确定。由于您没有指定值,因此选择.xlsx的默认值。文档列出了可能的值。您需要使用xlOpenXMLWorkbookMacroEnabled
。
代码将是:
xlOpenXMLWorkbookMacroEnabled = 52
....
wb.SaveAs(filename, FileFormat=xlOpenXMLWorkbookMacroEnabled)