先说解决办法:
pip install lxml
报错截图:
当时在两个环境中分别使用相同版本openpyxl,相同的代码,一个环境中能成功,另外一个一直报错。
排查结果如下:
根据报错找到文件: File "\openpyxl\worksheet_writer.py", line 147, in write_row
在155行到158行看到如下代码:
if LXML:
write_cell = lxml_write_cell
else:
write_cell = etree_write_cell
根据这一行报错: File "D:\Users\workspace\venv_my\vent_fastapi\lib\site-packages\openpyxl\cell_writer.py", line 82, in etree_write_cell
推测是此处应该要使用lxml_write_cell,改成如下再执行:
if LXML:
write_cell = lxml_write_cell
else:
write_cell = lxml_write_cell
ok,不报错了。
再往上找到LXML
的定义处
LXML = lxml_available() and lxml_env_set()
分别找到这两个函数的定义,检查处理逻辑,其中第一个函数取值如下:
def lxml_available():
try:
from lxml.etree import LXML_VERSION
LXML = LXML_VERSION >= (3, 3, 1, 0)
if not LXML:
import warnings
warnings.warn("The installed version of lxml is too old to be used with openpyxl")
return False # we have it, but too old
else:
return True # we have it, and recent enough
except ImportError:
return False # we don't even have it
发现需要导入lxml,估计时某个环境没有安装,直接pip install lxml
后再次执行,解决~