3

I have created endpoint to fetch data from database and download data in excel file using xmlswriter library. But rather than downloading the excel file it download text file with name 'unknown.txt' that includes data like::

"xl/workbook.xml�Q�N�0����4���T�%*!�P�#2����ؑ���Y�J)��ɞ����x�<4�|�u��&�����w}_?^�P�<ӂ)���GptY^-zc���� �+h�};�"�kh���4�T�6�"

I have tried all the sample code mentioned in commented code below: Code:

@app.route("/api/v1/downloadexcel", methods=["GET"])
def excel_download2():   
    date_from = request.args.get("date_from")
    date_to = request.args.get("date_to")

    try:
        data_to_create_excel= get_data(date_from, date_to)
      
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})

        # workbook = xlsxwriter.Workbook('demo.xlsx')

        worksheet = workbook.add_worksheet('data_to_create_excel')
        headers = list(data_to_create_excel[0].keys()) if len(data_to_create_excel) else []
        rows = [data .values() for data in data_to_create_excel]
        for row_num, row_data in enumerate([headers , *rows]):
            for col_num, col_data in enumerate(row_data):
                worksheet.write(row_num, col_num, col_data)


        workbook.close()
        output.seek(0)
        return send_file(output, attachment_filename="output.xlsx", as_attachment=True)

        # return Response(output.getvalue(), mimetype="application/ms-excel",
        #                 headers={"Content-Disposition": "attachment;filename=employee_report.xlsx"})

        # self.send_response(200)
        # self.send_header("Access-Control-Expose-Headers", "Content-Disposition")
        # self.send_header('Content-Disposition', 'attachment; filename=test.xlsx')
        # self.send_header('Content-type',
        #                  'application/ms-excel')
        # self.end_headers()
        # self.wfile.write(output.read())
        # return

        # file_name = 'ore_data_{}.xlsx'.format(
        #     datetime.now().strftime('%d/%m/%Y'))
        # return jsonify([csv_headers]), 200
        # return send_file(output,
        #                  attachment_filename='your_filename.xlsx',
        #                  as_attachment=True)
        # return Response(
        #     output.getvalue(),
        #     # mimetype='application/ms-excel',
        #     headers={
        #         "Access-Control-Expose-Headers": "Content-Disposition",
        #         "Content-Disposition": 'attachment; filename=test.xlsx',
        #         'Content-type':
        #     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        #     },
        # )
        # return output.read(),200
    except Exception as e:
        print(e)

1 Answers1

0

Add your data in a pandas dataframe. Far more easier to deal with columns etc. Then use the to_excel function. Then use send_from_directory (as you are doing) to send the file.

  • I am trying to generate an excel on the fly. I don't want to save file on disc. I want to store in memory and export it. I am still getting same error. – ashnav msit Jan 07 '21 at 22:59