如何在Flask中从服务器创建Excel文件并将其发送到客户端

时间:2019-12-12 12:38:49

标签: python flask flask-sqlalchemy

对于发送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>

1 个答案:

答案 0 :(得分:0)

此代码权限数据样本已转换为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

最诚挚的问候