后端实现
@app.route('/download_report_list', methods=['POST'])
def download_report_list():
from flask import jsonify, send_file
from openpyxl import Workbook
import io
report_list = []
try:
report_list = mysql().get_data("select * from csdn_table")
except Exception as e:
return e
wb = Workbook()
ws = wb.active
# 设置列标题
header = list(report_list[0].keys())
ws.append(header)
# 遍历数据并填充到工作表中
for row_data in report_list:
ws.append(list(row_data.values()))
# 将Workbook写入一个BytesIO对象
output = io.BytesIO()
wb.save(output)
# 将文件指针重新置于开头
output.seek(0)
# 返回文件内容,设置正确的MIME类型和文件名
return send_file(output, as_attachment=True, attachment_filename='csdn.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
前端实现
let download_data = window.report_list.join()
// 模拟表单提交事件
let form = document.createElement('form');
form.method = 'POST';
form.action = `/csdn_api/download_report_list`;
let input = document.createElement('input');
input.type = 'text';
input.name = 'report_guids';
input.value = download_data;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
setTimeout(() => {
document.body.removeChild(form);
}, 500);