create excel file from DataFrame and allow download in flask, error: file format/extension not valid

create excel file from DataFrame and allow download in flask, error: file format/extension not valid

我创建了一个简单的 Flask 应用程序,可以将 Pandas 数据框转换为 excel 文件。当我转到 link 时,该文件已下载,但是,我在尝试打开该文件时遇到以下错误:

Excel cannot open the file 'df.xlsx' because the file format or file extension is not valid. Verify that the files has not been corrupted and that the file extension matches the format of the file.

我是不是漏掉了什么?

 @app.route('/download', methods=["GET"])
 def download_excel():
    df = pd.DataFrame({'Name': ['Tesla','Tesla','Toyota','Ford','Ford','Ford'],
                   'Type': ['Model X','Model Y','Corolla','Bronco','Fiesta','Mustang']})

    #create an output stream
    output = BytesIO()
    writer = pd.ExcelWriter(df, engine='xlsxwriter')
    df.to_excel(writer, sheet_name='Sheet1')

    #the writer has done its job
    writer.close

    #go back to the beginning of the stream
    output.seek(0)
    
    #finally return the file
    return send_file(output, attachment_filename="df.xlsx", as_attachment=True)

问题是您将数据帧传递给 ExcelWriterpath 参数而不是 BytesIO 对象 (output)。

writer = pd.ExcelWriter(df, engine='xlsxwriter')

The ExcelWriter documentationpath 参数上表示以下内容:

path: str or typing.BinaryIO Path to xls or xlsx or ods file.


所以你可以这样做:

from flask import Flask, send_file
import pandas as pd
from io import BytesIO

app = Flask(__name__)


@app.route("/download", methods=["GET"])
def download_excel():
    df = pd.DataFrame(
        {
            "Name": ["Tesla", "Tesla", "Toyota", "Ford", "Ford", "Ford"],
            "Type": ["Model X", "Model Y", "Corolla", "Bronco", "Fiesta", "Mustang"],
        }
    )

    output = BytesIO()

    with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
        df.to_excel(writer, sheet_name="Sheet1")

    output.seek(0)

    return send_file(output, attachment_filename="df.xlsx", as_attachment=True)