解决pandas读取上传的excel报错BadZipFile(“File is not a zip file“) zipfile.BadZipFile: File is not a zip file

业务需求是从页面上下载一个表格模板,编辑后,再上传到后台进行解析,将表格内的内容存储在数据库。但是在后台解析的时候出现报错。

刚开始使用的是

import pandas as pd
df1 = pd.read_excel(
                filename,
                engine='openpyxl',
                index_col=0
            )

这种情况一直报错显示BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file

追踪源码发现后台是判断了读取excel的引擎,没有传入的情况下,默认使用的是xlrd

"""
_engines = {
        "xlrd": _XlrdReader,
        "openpyxl": _OpenpyxlReader,
        "odf": _ODFReader,
        "pyxlsb": _PyxlsbReader,
    }
""" 

def __init__(self, path_or_buffer, engine=None):
    if engine is None:
        engine = "xlrd"
        if isinstance(path_or_buffer, (BufferedIOBase, RawIOBase)):
            if _is_ods_stream(path_or_buffer):
                engine = "odf"
        else:
            ext = os.path.splitext(str(path_or_buffer))[-1]
            if ext == ".ods":
                engine = "odf"
    if engine not in self._engines:
        raise ValueError(f"Unknown engine: {engine}")

所以我就想不传入引擎,pip安装xlrd,使用默认的,继续报错

xlrd.biffh.XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'<html x...

原因就是这个文件虽然是xls结尾,但是内容并不是xls格式的,里面内容嵌套了很多的其他格式,然后使用pandas的read_html方法,因为我上传的excel就是html转换来的。继续测试,又提示缺lxml包,继续安装,安装完毕,记得重启pycharm。

df1 = pd.read_html(
                filename
            )

再次测试发现可以成功读取到上传的excel的数据了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值