业务需求是从页面上下载一个表格模板,编辑后,再上传到后台进行解析,将表格内的内容存储在数据库。但是在后台解析的时候出现报错。
刚开始使用的是
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的数据了。