1

我正在使用Flask 服务器和 xlsxwriter 重用此处发布的一些代码 Excel 导出

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

app = Flask(__name__)
@app.route('/')

def index():

    #create a random Pandas dataframe
    df_1 = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))

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

    #taken from the original question
    df_1.to_excel(writer, startrow = 0, merge_cells = False, sheet_name = "Sheet_1")
    workbook = writer.book
    worksheet = writer.sheets["Sheet_1"]
    format = workbook.add_format()
    format.set_bg_color('#eeeeee')
    worksheet.set_column(0,9,28)

    #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="testing.xlsx", as_attachment=True)

app.run(debug=True)

我正在运行 Ubuntu 18,我的代码位于 docker 容器中。不幸的是,此代码不会下载 xlsx 文件。它会下载整个存档,例如带有子文件夹等。因此我在 send_file 中使用 mimetype 但没有成功。我的设置可能有什么问题。有趣的是,我可以直接在 LibreOffice Calc 中打开存档,然后得到我期望看到的工作表。我还尝试将 BytesIO 在本地导出到实际文件中并发送该文件,但没有成功。可能是浏览器的问题?

4

1 回答 1

2

由于您要发送.xlsx(Microsoft Excel OpenXML)而不是.xls(Microsoft Excel),我认为您必须强制使用正确的mimetype参数send_file()

[..]
#finally return the file
    return send_file(output,
                     attachment_filename="testing.xlsx",
                     mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", # here
                     as_attachment=True)

参考https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

于 2020-06-27T09:41:44.757 回答