pandas xlsx转xls过程报错原因溯源与解决方案

引言

代码如下所示

inpath = r"h:/1.xlsx"
excel = pandas.read_excel(inpath)
excel.to_excel("h:/1.xls", index=None)

报错信息如下所示:

Traceback (most recent call last):
  File "D:\Software\python310\lib\site-packages\pandas\io\excel\_base.py", line 1111, in __new__
    engine = config.get_option(f"io.excel.{ext}.writer", silent=True)
  File "D:\Software\python310\lib\site-packages\pandas\_config\config.py", line 261, in __call__
    return self.__func__(*args, **kwds)
  File "D:\Software\python310\lib\site-packages\pandas\_config\config.py", line 135, in _get_option
    key = _get_single_key(pat, silent)
  File "D:\Software\python310\lib\site-packages\pandas\_config\config.py", line 121, in _get_single_key
    raise OptionError(f"No such keys(s): {repr(pat)}")
pandas._config.config.OptionError: No such keys(s): 'io.excel.xls.writer'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "E:\StudyCode\Python\myStudy\work\xlsx2xls.py", line 7, in <module>
    excel.to_excel("h:/1.xls", index=None)
  File "D:\Software\python310\lib\site-packages\pandas\core\generic.py", line 2252, in to_excel
    formatter.write(
  File "D:\Software\python310\lib\site-packages\pandas\io\formats\excel.py", line 934, in write
    writer = ExcelWriter(  # type: ignore[abstract]
  File "D:\Software\python310\lib\site-packages\pandas\io\excel\_base.py", line 1115, in __new__
    raise ValueError(f"No engine for filetype: '{ext}'") from err
ValueError: No engine for filetype: 'xls'

报错原因

pandas版本太高了,当我把pandas降级到1.5.2版本,重新执行代码,会发出如下警告:

FutureWarning: As the xlwt package is no longer maintained, the xlwt engine will be removed in a future version of pandas. This is the only engine in pandas that supports writing in the xls format. Install openpyxl and write to an xlsx file instead. You can set the option io.excel.xls.writer to 'xlwt' to silence this warning. While this option is deprecated and will also raise a warning, it can be globally set and the warning suppressed.
  excel.to_excel("h:/1.xls", index=None)

但是文件已经生成了。

解决方案

降级pandas至1.5.2

小聪明

python310\lib\site-packages\pandas\io\excel中的init文件中添加了register_writer(_XlwtWriter)也是没有用的,具体怎么注册的没时间看了,先干完活再说吧。T_T

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。