如何使用 OpenPyXL 使用临时文件加载工作簿



在我的烧瓶网络应用程序中,我正在将数据从 excel 写入一个临时文件,然后在内存中解析该文件。此方法适用于 xlrd,但不适用于 openpyxl。

以下是我如何写入一个临时文件,然后使用 xlrd 解析该文件。

xls_str = request.json.get('file')
try:
xls_str = xls_str.split('base64,')[1]
xls_data = b64decode(xls_str)
except IndexError:
return 'Invalid form data', 406
save_path = os.path.join(tempfile.gettempdir(), random_alphanum(10))
with open(save_path, 'wb') as f:
f.write(xls_data)
f.close()
try:
bundle = parse(save_path, current_user)
except UnsupportedFileException:
return 'Unsupported file format', 406
except IncompatibleExcelException as ex:
return str(ex), 406
finally:
os.remove(save_path)]

当我将 openpyxl 与上面的代码一起使用时,它会抱怨不受支持的类型,但那是因为我使用临时文件来解析数据,因此它没有".xlsx"扩展名,即使我添加了它,它也不会工作,因为它毕竟不是 excel 文件。

openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support file format, 
please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm

我该怎么办?

为什么不使用openpyxl创建一个临时的Excel文件。试试这个例子。我过去做过类似的事情。

from io import BytesIO
from openpyxl.writer.excel import save_virtual_workbook
from openpyxl import Workbook

def create_xlsx():
wb = Workbook()
ws = wb.active
row = ('Hello', 'Boosted_d16')
ws.append(row)
return wb
@app.route('/',  methods=['GET'])
def main():
xlsx = create_xlsx()
filename = BytesIO(save_virtual_workbook(xlsx))
return send_file(
filename,
attachment_filename='test.xlsx',
as_attachment=True
)

最新更新