首页 > 解决方案 > Win32Com:添加一个新的 Excel 文件并另存为 .xlsm

问题描述

我在 Python 中使用 Win32com。

基本上我想创建一个新的 .xlsm 工作簿。

1)但是SaveAs对我不起作用,我总是遇到以下错误

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Microsoft Excel cannot access the file 'C:\\//Users/~/322DF100'. There are several possible reasons:\n\n• The file name or path does not exist.\n• The file is being used by another program.\n• The workbook you are trying to save has the same name as a currently open workbook.", 'xlmain11.chm', 0, -2146827284), None)

import win32com.client as w3c
xl=w3c.DispatchEx("Excel.Application")
xl.DisplayAlerts=False


wb = xl.Workbooks.Add()
wb.SaveAs ('C:/Users/~/OUTPUT8.xlsm')
wb.Close(SaveChanges=False)

del wb
xl.Application.Quit()
del xl



2) SaveCopyAs 有效,但我无法打开文件
Excel 无法打开文件,因为文件格式或扩展名无效。

import win32com.client as w3c
xl=w3c.DispatchEx("Excel.Application")
xl.DisplayAlerts=False


wb = xl.Workbooks.Add()
wb.SaveCopyAs ('C:/Users/~/OUTPUT8.xlsm')
wb.Close(SaveChanges=False)

del wb
xl.Application.Quit()
del xl

标签: pythonexcelwin32com

解决方案


推荐阅读