gpt4 book ai didi

python-3.x - Flask 对 excel 文件的响应给我损坏的 excel 响应

转载 作者:行者123 更新时间:2023-12-04 19:50:23 31 4
gpt4 key购买 nike

我已经创建端点以使用 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)

最佳答案

将您的数据添加到 pandas 数据框中。更容易处理列等。然后使用 to_excel功能。然后使用 send_from_directory(正如您正在做的那样)发送文件。

关于python-3.x - Flask 对 excel 文件的响应给我损坏的 excel 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65365974/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com