本文介绍: 【代码】Flask+vue+axios完成导出Excel表格的功能。
前段部分:
1.分装api:在 src/api/volunteer.js文件内
注意:一定要加上” responseType: ‘blob’ “否则打开文件后是乱码或者根本打不开文件
import request from "@/utils/request";
//导出
export function importVolunteer(data) {
return request({
method: 'post',
url: '/volunteer/download_excel',
data,
responseType: 'blob'
})
}
2. 调用接口 :在src/views/volunteer.vue文件内
// 导出按钮点击事件处理
async importHandle() {
try {
// 调用导出的接口
const res = await importVolunteer();
// 处理导出的Excel文件
const blob = new Blob([res], {type:'application/vnd.ms-excel;charset=utf-8'});
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', '志愿者导出表');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
}
}
后端部分:
第一种:不存储在后端直接返回给前端
import io
import xlwt as xlwt
from flask import make_response
from flask_backend.models import Volunteer
@volunteer_blue.route('/download_excel', methods=['POST'])
def exportData():
wb = xlwt.Workbook()
ws = wb.add_sheet('志愿者报表')
first_col = ws.col(0) # xlwt中是行和列都是从0开始计算的
second_col = ws.col(1)
third_col = ws.col(2)
four_col = ws.col(3)
five_col = ws.col(4)
six_col = ws.col(5)
seven_col = ws.col(6)
first_col.width = 128 * 20
second_col.width = 230 * 20
third_col.width = 230 * 20
four_col.width = 128 * 20
five_col.width = 230 * 20
six_col.width = 230 * 20
seven_col.width = 230 * 20
ws.write(0, 0, "id")
ws.write(0, 1, "姓名")
ws.write(0, 2, "性别")
ws.write(0, 3, "身份证号码")
ws.write(0, 4, "电话号码")
ws.write(0, 5, "审核状态")
ws.write(0, 6, "注册时间")
dataw = Volunteer.query.order_by(Volunteer.id).all()
if dataw is not None:
for i in range(0, len(dataw)):
pet = dataw[i]
repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
ws.write(i + 1, 0, pet.id)
ws.write(i + 1, 1, pet.name)
ws.write(i + 1, 2, pet.gender)
ws.write(i + 1, 3, pet.id_card)
ws.write(i + 1, 4, pet.phone)
ws.write(i + 1, 5, status)
ws.write(i + 1, 6, repairDate)
# 创建一个内存中的文件对象
file_obj = io.BytesIO()
wb.save(file_obj)
file_obj.seek(0)
# 创建响应对象
response = make_response(file_obj.getvalue())
# 设置Content-Type和Content-Disposition头信息
response.headers['Content-Type'] = 'application/vnd.ms-excel'
response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'
return response
第二种:存储在后端然后再返回给前端
import os
import time
import xlwt as xlwt
from flask import send_file, make_response
from flask_backend.models import Volunteer
@volunteer_blue.route('/download_excel', methods=['POST'])
def exportData():
wb = xlwt.Workbook()
ws = wb.add_sheet('志愿者报表')
first_col = ws.col(0) # xlwt中是行和列都是从0开始计算的
second_col = ws.col(1)
third_col = ws.col(2)
four_col = ws.col(3)
five_col = ws.col(4)
six_col = ws.col(5)
seven_col = ws.col(6)
first_col.width = 128 * 20
second_col.width = 230 * 20
third_col.width = 230 * 20
four_col.width = 128 * 20
five_col.width = 230 * 20
six_col.width = 230 * 20
seven_col.width = 230 * 20
ws.write(0, 0, "id")
ws.write(0, 1, "姓名")
ws.write(0, 2, "性别")
ws.write(0, 3, "身份证号码")
ws.write(0, 4, "电话号码")
ws.write(0, 5, "审核状态")
ws.write(0, 6, "注册时间")
dataw = Volunteer.query.order_by(Volunteer.id).all()
if dataw is not None:
for i in range(0, len(dataw)):
pet = dataw[i]
repairDate = pet.register_time.strftime('%Y-%m-%d %Z %H:%M:%S') if pet.register_time else ''
status = '已审核' if pet.check_status == 1 else '未审核' if pet.check_status == 0 else ''
ws.write(i + 1, 0, pet.id)
ws.write(i + 1, 1, pet.name)
ws.write(i + 1, 2, pet.gender)
ws.write(i + 1, 3, pet.id_card)
ws.write(i + 1, 4, pet.phone)
ws.write(i + 1, 5, status)
ws.write(i + 1, 6, repairDate)
now = str(time.time())
path = "/static/excel/"
fileName = "repair_" + now + ".xls"
file_path = os.path.dirname(__file__) + path
if not os.path.exists(file_path):
os.makedirs(file_path)
file_path = file_path + fileName
try:
f = open(file_path, 'r')
f.close()
except IOError:
f = open(file_path, 'w')
wb.save(file_path)
# 创建响应对象
response = make_response(send_file(file_path, as_attachment=True))
# 设置Content-Type和Content-Disposition头信息
response.headers['Content-Type'] = 'application/vnd.ms-excel'
response.headers['Content-Disposition'] = 'attachment; filename="repair.xls"'
return response
原文地址:https://blog.csdn.net/qq_44906497/article/details/134866960
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_50517.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。