我已经创建了端点来从数据库中获取数据,并使用xmlswriter库下载excel文件中的数据。但它不是下载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)
发布于 2020-12-19 05:04:54
将您的数据添加到pandas数据帧中。更容易处理列等,然后使用to_excel函数。然后使用send_from_directory (就像您正在做的那样)发送文件。
https://stackoverflow.com/questions/65365974
复制相似问题