簡體   English   中英

如何在 Flask 中創建 Excel 文件並將其從服務器發送到客戶端

[英]How to create and send excel file from server to client in flask

為了發送 CSV 文件,我已經這樣做了並且工作正常

        @app.route('/downloadFile' , methods=['GET'])
        def downloadFile():
            csvList = [[ 's' , 12], ['r' , 20 ]]
            csvHeader = [['name', 'age']]
            si = StringIO.StringIO()
            cw = csv.writer(si, delimiter=',', quotechar=':', quoting=csv.QUOTE_MINIMAL)
            cw.writerows(csvHeader)
            cw.writerows(csvList)
            print(si.getvalue())
            output = make_response(si.getvalue())
            output.headers["Content-Disposition"] = "attachment; filename=report.csv"
            output.headers["Content-type"] = "text/csv"

但是當我以 excel 格式執行上述解決方案時它不起作用,數據格式無效

    @app.route('/downloadFileExcel' , methods=['GET'])
    def downloadFileExcel():
    csvList = [[ 's' , 12], ['r' , 20 ]]
    si = StringIO.StringIO()
    cw = csv.writer(si)
    cw.writerows(csvList)
    print(si.getvalue())
    output = make_response(si.getvalue())
    output.headers["Content-Disposition"] = "attachment; filename=report.xls"
    output.headers["Content-type"] = "application/vnd.ms-excel" 

在客戶端

<a id="Link" href="/downloadFileExcel" >
  <li id ="excel">Excel</li>
</a>
<a id="Link" href="/downloadFile" >
<li  id="csv" > CSV</li>
</a>

此代碼示例將數據正確放入 xlsx 文件中

@app.route('/downloadFile' , methods=['GET'])
def downloadFileExcel():
    csvList = [['s', 12], ['r', 20]]
    name = uuid.uuid4()
    writer = xlsxwriter.Workbook("/tmp/%s" % name)
    worksheet = writer.add_worksheet()
    for i, row in enumerate(csvList):
        worksheet.write_row(i, 0, row)
    writer.close()

    f = open("/tmp/%s" % name, 'rb')
    output = flask.make_response(f.read())
    output.headers["Content-Disposition"] = "attachment; filename=report.xlsx"
    output.headers["Content-type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    f.close()

    return output

小心將標題內容類型更改為application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

最好的祝福

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM