烧瓶对 excel 文件的响应给我损坏的 excel 响应



我创建了端点来从数据库中获取数据并使用xmlswriter库下载excel文件中的数据。但是,它不是下载 excel 文件,而是下载名称为"unknown.txt"的文本文件,其中包含以下数据:

"xl/workbook.xml Q N 0 4 T %*! P #2 ؑ Y J) ɞ x <4 | u & w}_?^ P <ʂ)>

我已经尝试了下面注释代码中提到的所有示例代码: 法典:

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

在熊猫数据帧中添加数据。处理列等要容易得多。然后使用to_excel函数。然后使用send_from_directory(就像您正在做的那样)发送文件。

最新更新