python - python中的.xlsx下载问题
问题描述
我是 Python 开发的新手。
我正在用 Python 开发一个烧瓶 API,这将有助于下载一个.xlsx
格式的 excel 文件。我的代码正在生成.xlsx
格式文件,但是当我下载报告时出现错误:"File format or file extensions are not valid. Verify the file has not been corrupted"
.
请帮助我。
import io
import pandas as pd
from flask import send_file
def get_data():
buf = io.BytesIO()
with pd.ExcelWriter(buf, date_format='dd/mm/yyyy', datetime_format='dd/mm/yyyy') as test:
dtl_ext = detail.to_excel(test, index=False,encoding='utf-16')
detail_rec.save()
excel_data = buf.getvalue()
buf.seek(0)
return send_file(
buf,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
attachment_filename='test11.xlsx',
as_attachment=True,
cache_timeout=0
)
解决方案
您可以使用以下库使其更容易:
- http://flask.pyexcel.org/en/latest/
- https://github.com/pyexcel/pyexcel-xls
- https://github.com/pyexcel/pyexcel-xlsx
安装它们之后(检查链接)。通过以下方式在 Python 中导入它们:
import flask_excel as excel
import pyexcel.ext.xls
import pyexcel.ext.xlsx
然后:
@app/route('/download', methods=['GET'])
def download_data():
sample_data=[0, 1, 2]
excel.init_excel(app)
extension_type = "xlsx"
filename = "test123" + "." extension_type
d = {'colName': sample_data}
return excel.make_response_from_dict(d, file_type=extension_type, file_name=filename)
# check the flask-excel library from different export option.
# This one uses a dictionary of lists.
# You can do a lists of dictionary, simply an array, so on and so forth
推荐阅读
- java - Microsoft Oauth2 403 禁止
- c# - 选择器在第二次单击时设置 selectedItem [Xamarin]
- unit-testing - 如何对一个类的方法进行单元测试,该方法又调用另一个类的方法
- r - 将样本随机分配到 R 中的组中
- python - 将二叉树转换为完整二叉树的函数?
- c# - 如何让 npc 用头部或使用 transform.lookat 来查看代理?
- hyperledger-fabric - fabric 2.0 无法生成创世块,没有定义策略
- python - 我正在尝试使用模块 simplegui 在 CodeSkulptor 中制作一个带有两个输入字段的计算器。我不知道我做错了什么
- python - 使用字典映射 Pandas 列的最佳方法
- swift - 在自定义类 swift 中支持 for-each