Python win32com'参数数量无效'

我正在尝试使用win32com将多个xlsx文件转换为xls使用以下代码:

import win32com.client f = r"./input.xlsx" xl = win32com.client.gencache.EnsureDispatch('Excel.Application') wb = xl.Workbooks.Open(f) xl.ActiveWorkbook.SaveAs("./somefile.xls", FileFormat=56) 

这是与以下错误失败:

 Traceback (most recent call last): File "xlsx_conv.py", line 6, in <module> xl.ActiveWorkbook.SaveAs("./somefile.xls", FileFormat=56) File "C:\python27\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x9.py", line 46413, in SaveAs , Local, WorkIdentity) pywintypes.com_error: (-2147352562, 'Invalid number of parameters.', None, None) 

一些更多细节:

我可以对工作簿执行其他命令,例如wb.Worksheets.Add()并设置xl.Visible=True来查看工作簿。 甚至做wb.Save()但是不能做一个wb.SaveAs()

COMexception是由于缺less文件名参数,因为f = r"./input.xlsx"找不到。 如果您使用Excel 2013+,您将收到一个更精确的exception消息,并显示稍微不同的错误代码:

(-2147352567,'Exception occurred。',(0,'Microsoft Excel','对不起,我们找不到./input.xlsx。是否有可能移动,重命名或删除?','xlmain11.chm' ,0,-2146827284),无)

虽然你的path在Python的本地环境中工作,指向被调用的.py脚本所在的目录,但是它不需要像Windows COM这样的外部API,因为需要完整path。

要解决这个问题,可以考虑使用Python内置的os来提取脚本的当前目录path,并在Excel COM方法中与os.path.join()连接。 另外,无论是否引发exception,下面都使用try/except/finally来正确结束后台的Excel.exe进程。

 import os import win32com.client as win32 cd = os.path.dirname(os.path.abspath(__file__)) try: f = os.path.join(cd, "input.xlsx") xl = win32.gencache.EnsureDispatch('Excel.Application') wb = xl.Workbooks.Open(f) xl.ActiveWorkbook.SaveAs(os.path.join(cd, "input.xls"), FileFormat=56) wb.Close(True) except Exception as e: print(e) finally: wb = None xl = None 

我花了很多时间寻找适当的解决scheme,但我唯一发现的是我昨天写的脚本没有工作。 另外,同样的脚本在其他计算机上工作,所以我想这是在Windows / MsExcel / Python环境中被打破,但我不知道在哪里。

我find了一个“SaveAs”问题的工作,只是使用“保存”function。 幸运的是,这仍然有效,并没有阻止我继续我的任务。 我希望这个帮助。

 import win32com.client as win32 from shutil import copyfile # you need to define these two: # src, is the absolute path to the excel file you want to open. # dst, is the where you want to save as the file. copyfile(src, dst) excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Workbooks.Open(PATH_DATASET_XLS) ws = wb.Worksheets(DATASET_WORKING_SHEET) # do some stuff ws.Cells( 1, 'A' ).Value = "hello" # Saving changes wb.Save() # <- this is the work around excel.Application.Quit()