使用xlwings打开.xlsm文件时遭遇COM错误的技术求助
问题:xlwings打开.xlsm文件时触发COM错误(-2146959355)
错误详情
运行代码尝试打开.xlsm格式Excel文件时,持续出现以下COM错误:
öffnen Traceback (most recent call last): File "C:\MyPath\Desktop\Controling\Script\Releas_Build\services\excel_service.py", line 40, in <module> ExcelService() File "C:\MyPath\Desktop\Controling\Script\Releas_Build\services\excel_service.py", line 29, in __init__ app = xl.App(visible=True) ^^^^^^^^^^^^^^^^^^^^ File "C:\MyPath\Python\Python311\site-packages\xlwings\main.py", line 312, in __init__ self.impl = engines.active.apps.add( ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\MyPath\Python\Python311\site-packages\xlwings\main.py", line 211, in add return App(impl=self.impl.add(**kwargs)) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\MyPath\Python\Python311\site-packages\xlwings\_xlwindows.py", line 510, in add return App(spec=spec, add_book=add_book, xl=xl, visible=visible) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\MyPath\Python\Python311\site-packages\xlwings\_xlwindows.py", line 563, in __init__ self._xl = COMRetryObjectWrapper(DispatchEx("Excel.Application")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\MyPath\Python\Python311\site-packages\win32com\client\__init__.py", line 142, in DispatchEx dispatch = pythoncom.CoCreateInstanceEx( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pywintypes.com_error: (-2146959355, 'Server execution failed', None, None)
环境信息
- 操作系统:Windows 11 Pro x64
- Excel版本:365
- Python版本:3.11.9
- xlwings版本:0.33.15
尝试的代码
import xlwings as xl import os class ExcelService: BASE_PATH = os.curdir EXCEL_SYS_PATH = "240401_Gesamtplanung vsSYS_Budget26_V4.xlsm" EXCEL_SW_PATH = "240401_Gesamtplanung vsSW_Budget26_V2.xlsm" def __init__(self): self.sys_full_path = os.path.join(self.BASE_PATH, self.EXCEL_SYS_PATH) self.sw_full_path = os.path.join(self.BASE_PATH, self.EXCEL_SW_PATH) if xl.apps: print("aktive") app = xl.apps.active if app.books: wb = app.books[0] else: wb = xl.Book(self.sw_full_path) else: print("öffnen") app = xl.App(visible=True) wb = app.books.open(self.sw_full_path) wb = xl.Book(self.sw_full_path) app = wb.app print(wb.sheets.active) print("Arbeitsmappe:", wb.name) print("Pfad:", wb.fullname) input("Drücke Enter zum Beenden…") # Damit das Fenster offen bleibt if __name__ == "__main__": ExcelService()
解决方法
1. 清理Excel后台进程
Server execution failed错误大多因后台残留Excel进程导致COM无法创建新实例。打开任务管理器,结束所有EXCEL.EXE进程后重新运行代码。
2. 修复代码重复打开问题
代码else分支中重复打开了同一文件,会导致实例冲突:
# 多余的重复调用,需移除 wb = xl.Book(self.sw_full_path)
修改后代码:
else: print("öffnen") app = xl.App(visible=True) wb = app.books.open(self.sw_full_path)
3. 以管理员身份运行脚本
Windows权限限制可能导致无法创建Excel COM对象,右键点击终端或脚本,选择「以管理员身份运行」。
4. 修复Office安装
若上述方法无效,打开控制面板→程序和功能→找到Microsoft 365→右键选择「更改」→执行「快速修复」或「联机修复」。
5. 确保文件路径正确
使用绝对路径避免相对路径指向错误:
BASE_PATH = os.path.abspath(os.curdir)
内容的提问来源于stack exchange,提问作者XlordXtgX
相关产品推荐
相关产品推荐

