python版本
python3.7
代码应该是能 python3.x 通用,有问题请提出宝贵修改意见
依赖包
pip install flask
pip install xlsxwriter
代码:
from io import BytesIO
from urllib.parse import qoute
from flask import make_response
from app.models import Goods
import xlsxwriter
import datetime
import mimetypes
# 想要使用flask send_file, methods只能用GET
@export.route("/export/excel", methods=["GET"])
def export_excel():
id = request.values.get("id", "", type=str)
out = BytesIO()
# 实例化二进制数据
out = BytesIO()
# 创建一个Excel实例
workbook = xlsxwriter.Workbook(out)
# 添加一个sheet,add_worksheet(),默认"Sheet1",可自定义命名,add_worksheet("资产列表")
table = workbook.add_worksheet()
# table.write(行, 列, 字段名)
# 行、列从 0 开始计数
# 字段命名根据每个人使用情况而定,插入数据部分也是
table.write(0, 0, "资产编号")
table.write(0, 1, "资产名称")
table.write(0, 2, "类型")
table.write(0, 3, "记录值")
table.write(0, 4, "所属部门")
table.write(0, 5, "负责人")
table.write(0, 6, "联系方式")
row = 1
for i in id.split(","):
goods = Goods.query.get(i)
table.write(row, 0, goods.id)
table.write(row, 1, goods.name)
table.write(row, 2, goods.record_type)
table.write(row, 3, goods.value)
table.write(row, 4, goods.department)
table.write(row, 5, goods.owner)
table.write(row, 6, goods.phone)
row += 1
workbook.close()
filename = quote("资产列表_{}.xlsx".format(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
file = make_response(out.getvalue())
out.close()
mime_type = mimetypes.guess_type('%s.xlsx' % filename)[0]
file.headers['Content-Type'] = mime_type
file.headers["Cache-Control"] = "no-cache"
file.headers['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(filename)
return file
网友评论