“单元格写入”组件运行报错解决方案

最近自己开发中遇到的一个怪异问题,运行“单元格写入”组件总是报错。报错信息如下:

Traceback (most recent call last):
  File "D:\Program Files\IS-RPA10\Project\sms\codes\Main.py", line 155, in <module>
    pro.Main()
  File "D:\Program Files\IS-RPA10\Project\sms\codes\Main.py", line 113, in Main
    iexcel.write_cell(path='D:/Program Files/IS-RPA10/Project/sms/codes/短信发送结果记录表.xlsx',text="验证码短信已成功转发到指定微信群",file_type='excel')
  File "D:\Program Files\IS-RPA10\Python\lib\ubpa\iexcel.py", line 87, in write_cell
  File "D:\Program Files\IS-RPA10\Python\lib\ubpa\iexcel.py", line 69, in write_cell
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\xlwings\main.py", line 479, in __init__
    app = App(add_book=False)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\xlwings\main.py", line 204, in __init__
    self.impl = xlplatform.App(spec=spec, add_book=add_book)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\xlwings\_xlwindows.py", line 288, in __init__
    self._xl = COMRetryObjectWrapper(DispatchEx('Excel.Application'))
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\__init__.py", line 114, in DispatchEx
    return Dispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\__init__.py", line 96, in Dispatch
    return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\__init__.py", line 37, in __WrapDispatch
    klass = gencache.GetClassForCLSID(resultCLSID)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\gencache.py", line 183, in GetClassForCLSID
    mod = GetModuleForCLSID(clsid)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\gencache.py", line 226, in GetModuleForCLSID
    mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\gencache.py", line 266, in GetModuleForTypelib
    AddModuleToCache(typelibCLSID, lcid, major, minor)
  File "D:\Program Files\IS-RPA10\Python\lib\site-packages\win32com\client\gencache.py", line 558, in AddModuleToCache
    dict = mod.CLSIDToClassMap
AttributeError: module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9' has no attribute 'CLSIDToClassMap'

然后审核遇到其他老师的应用,只要遇到表格就都崩倒了,发生这个错误的原因并不是很清楚, 大概是上周升级了一下系统, 但是我并不清楚内部原因。

解决的方法就是, 因为这个缓存的文件有问题, 所以就应该删掉缓存. 所以我先找到这个缓存文件:

运行下面的代码:打印出缓存文件的路径

from win32com.client.gencache import EnsureDispatch

import sys

xl = EnsureDispatch("Word.Application")

print(sys.modules[xl.__module__].__file__)

运行结果:

“单元格写入”组件运行报错解决方案

然后根据打印的路径,删除有异常的缓存文件夹:
“单元格写入”组件运行报错解决方案

再次运行,程序跑通。

好了,下次分享再见。