Excel export with Flask server and xlsxwriter

后端 未结 3 1539
梦如初夏
梦如初夏 2021-02-01 09:41

So I\'ve been using XLSXWriter in the past to export an excel file containing one tab filled with two pandas dataframes. In the past I\'ve only been exporting the file to a loca

3条回答
  •  一向
    一向 (楼主)
    2021-02-01 10:32

    If you want xlsx file in response without storing it at the server side. You can use the following code snippet.

    from flask import Flask
    
    app = Flask(__name__)
    
    data = [[1, 2], [3, 4]]
    
    
    @app.route('/')
    def get_xslx_for_data():
        try:
            response = Response()
            response.status_code = 200
            output = StringIO.StringIO()
            workbook = xlsxwriter.Workbook(output, {'in_memory': True})
            worksheet = workbook.add_worksheet('hello')
            for i, d in enumerate(data):
                for j, res in enumerate(d):
                    worksheet.write(i, j, res)
            workbook.close()
            output.seek(0)
            response.data = output.read()
            file_name = 'my_file_{}.xlsx'.format(
                datetime.now().strftime('%d/%m/%Y'))
            mimetype_tuple = mimetypes.guess_type(file_name)
            response_headers = Headers({
                'Pragma': "public",  # required,
                'Expires': '0',
                'Cache-Control': 'must-revalidate, post-check=0, pre-check=0',
                'Cache-Control': 'private',  # required for certain browsers,
                'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'Content-Disposition': 'attachment; filename=\"%s\";' % file_name,
                'Content-Transfer-Encoding': 'binary',
                'Content-Length': len(response.data)
            })
    
            if not mimetype_tuple[1] is None:
                response.update({
                    'Content-Encoding': mimetype_tuple[1]
                })
            response.headers = response_headers
            response.set_cookie('fileDownload', 'true', path='/')
            return response
        except Exception as e:
            print(e)
    
    
    if __name__ == '__main__':
        app.run()
    

提交回复
热议问题