简体   繁体   English

python中的.xlsx下载问题

[英].xlsx downloading issue in python

I am new to Python development.我是 Python 开发的新手。

I am developing a flask API in Python that will help to download one excel file in .xlsx format.我正在用 Python 开发一个 Flask API,这将有助于下载一个.xlsx格式的 excel 文件。 my code is generating the file in .xlsx format but when I downloading the report I am getting the error: "File format or file extensions are not valid. Verify the file has not been corrupted" .我的代码正在生成.xlsx格式的文件,但是当我下载报告时,我收到错误: "File format or file extensions are not valid. Verify the file has not been corrupted"

Please help me on this.请帮我解决这个问题。

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
        )

You can use the following libraries to make it easier:您可以使用以下库来简化操作:

After you have installed them (check the links for that).安装它们后(检查链接)。 Import them in Python in the following manner:按照以下方式在 Python 中导入它们:

  • import flask_excel as excel
  • import pyexcel.ext.xls
  • import pyexcel.ext.xlsx

Then:然后:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM