首页 > 解决方案 > 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
        )

标签: python

解决方案


您可以使用以下库使其更容易:

安装它们之后(检查链接)。通过以下方式在 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

推荐阅读