解决pandas.read_excel报错‘Must explicitly set engine if not passing in buffer or path for io.‘

本文介绍了一种在Docker环境下使用pandas读取xls文件并转换为DataFrame时遇到的问题及解决方案。当直接从requests获取的content读取时,会出现错误,必须明确指定engine或使用BytesIO来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

希望通过requests获取到xls,再通过pandas.read_excel转换为dataframe

>>> res = requests.get(url)
>>> df = pd.read_excel(result.content)

以上代码在本机上运行没有问题,但是,通过docker部署到服务器时报错:

  File "/usr/lib/python3/dist-packages/pandas/util/_decorators.py", line 208, in wrapper
    return func(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/pandas/io/excel/_base.py", line 310, in read_excel
    io = ExcelFile(io, engine=engine)
  File "/usr/lib/python3/dist-packages/pandas/io/excel/_base.py", line 819, in __init__
    self._reader = self._engines[engine](self._io)
  File "/usr/lib/python3/dist-packages/pandas/io/excel/_xlrd.py", line 21, in __init__
    super().__init__(filepath_or_buffer)
  File "/usr/lib/python3/dist-packages/pandas/io/excel/_base.py", line 361, in __init__
    raise ValueError(
ValueError: Must explicitly set engine if not passing in buffer or path for io.

设置engine后依旧报错

>>> df = pd.read_excel(result.content, engine='xlrd')

搜索后发现解决办法:

>>> BytesIO = pd.io.common.BytesIO
>>> df = pd.read_excel(BytesIO(result.content))

具体是为什么,还不清楚
参考:https://stackoverflow.com/a/50307531/7151777

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值