Python 并复活 'Invalid number of parameters'

Python win32com 'Invalid number of parameters'

我正在尝试使用 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[=13=]020813-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()

COM 异常是由于缺少文件名参数,因为找不到 f = r"./input.xlsx"。如果您使用 Excel 2013+,您会收到更精确的异常消息,错误代码略有不同:

(-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find ./input.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

虽然您的路径在 Python 指向被调用 .py 脚本所在目录的本机上下文中有效,但它不能与外部 API 接口,例如 Windows COM,因为需要完整路径。

解决,考虑使用Python内置的os提取脚本当前目录路径,并在ExcelCOM方法中与os.path.join()拼接.此外,下面使用 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

我花了很多时间寻找合适的解决方案,但我唯一发现的是我昨天写的脚本今天不起作用。此外,相同的脚本可以在其他计算机上运行,​​所以我猜这是在 windows/MsExcel/Python 环境中出现的问题,但我不知道在哪里。

我找到了解决 "SaveAs" 问题的方法,它只是使用 "Save"功能。幸运的是,它仍然有效并且不会阻止我继续我的任务。希望对您有所帮助。

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