Ответ Flask на файл Excel дает мне поврежденный ответ Excel

Я создал конечную точку для извлечения данных из базы данных и загрузки данных в файл Excel с помощью библиотеки xmlswriter. Но вместо того, чтобы загружать файл Excel, он загружает текстовый файл с именем unknown.txt, который включает такие данные, как ::

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

Я пробовал весь пример кода, упомянутый в закомментированном коде ниже: Код:

@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)

person ashnav msit    schedule 19.12.2020    source источник
comment
Удалось ли вам это решить? Я столкнулся с той же проблемой.   -  person Rabindra    schedule 16.06.2021


Ответы (1)


Добавьте свои данные в фреймворк pandas. Намного проще работать со столбцами и т. Д. Затем используйте to_excel. Затем используйте send_from_directory (как вы это делаете) для отправки файла.

person Abdur-Rahmaan Janhangeer    schedule 19.12.2020
comment
Я пытаюсь создать Excel на лету. Я не хочу сохранять файл на диск. Хочу сохранить в памяти и экспортировать. Я все еще получаю ту же ошибку. - person ashnav msit; 08.01.2021