Pywin32 Saving as XLSM file instead of XLSX

£可爱£侵袭症+ 提交于 2019-12-08 11:52:25

问题


When I currently attempt to save an XLSM file like so:

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()

I am given the following error...

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)

How do I save as a new file format?

Note- this causes the same error when trying to save a file that was already an XLSM, as an XLSM.


回答1:


The format of the file is determined by the FileFormat parameter that you specify when you call SaveAs. Since you don't specify a value, the default value of .xlsx is chosen. The documentation lists the possible values. You need to use xlOpenXMLWorkbookMacroEnabled.

The code would be:

xlOpenXMLWorkbookMacroEnabled = 52
....
wb.SaveAs(filename, FileFormat=xlOpenXMLWorkbookMacroEnabled)


来源:https://stackoverflow.com/questions/21306275/pywin32-saving-as-xlsm-file-instead-of-xlsx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!