这段代码
import win32com.client as win32
Excel = win32.gencache.EnsureDispatch('Excel.Application')
曾经可用,但现在会产生错误:
AttributeError: 'module' object has no attribute 'CLSIDToPackageMap'
发生了什么?
这段代码
import win32com.client as win32
Excel = win32.gencache.EnsureDispatch('Excel.Application')
曾经可用,但现在会产生错误:
AttributeError: 'module' object has no attribute 'CLSIDToPackageMap'
发生了什么?
Use the dynamic module to force your code to work in a late-bound oriented way. Example use:
"win32com.client.Dispatch()" instead of "win32.gencache.EnsureDispatch('Excel.Application')"
Use camelcase sensitive keywords for the early bound oriented way. Example use:
"excel.Visible()" instead of "excel.VISIBLE()" or "excel.visible()"
我猜,删除gen_py文件夹后第一次运行代码是有效的,但从第二次运行开始会抛出错误,因为win32.gencache.EnsureDispatch是一个早期绑定的Dispatch,所以gen_py文件夹会再次被创建。
我在Github讨论中找到了一种更优雅的解决方案,并将其合并到一个函数中。对我起作用了。
def dispatch(app_name:str):
try:
from win32com import client
app = client.gencache.EnsureDispatch(app_name)
except AttributeError:
# Corner case dependencies.
import os
import re
import sys
import shutil
# Remove cache and try again.
MODULE_LIST = [m.__name__ for m in sys.modules.values()]
for module in MODULE_LIST:
if re.match(r'win32com\.gen_py\..+', module):
del sys.modules[module]
shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
from win32com import client
app = client.gencache.EnsureDispatch(app_name)
return app
谢谢 - 在添加了您的函数并进行了此更改后,它像魔法一样奏效:
#excel = win32.gencache.EnsureDispatch('Excel.Application')
excel = dispatch('Excel.Application')
此致敬礼,
js