python中使用xlwt
库导出excel
1. 安装依赖包
pip install xlwt
2. 写入Excel数据返回前端
import xlwt
from flask import Flask
app = Flask(__name__)
@app.route('/api/exceptExcel', methods=['get'])
def exceptExcel():
# xlwt库将数据导入Excel
workbook = xlwt.Workbook()
# 添加一个表 参数为表名
worksheet = workbook.add_sheet('sheet1')
# 写列头,参数依次代表行,列,内容,格式(可省略,默认文本格式输出)
worksheet.write(0, 0, '列头1')
worksheet.write(0, 0, '列头2')
worksheet.write(0, 0, '列头3')
# 写入数据行
worksheet.write(1, 0, '1')
worksheet.write(1, 1, '2')
worksheet.write(1, 2, '3')
# xlwt不支持xlsx,只支持xls
# filePath = 'excel/excelTest.xls'
# 保存文件到本地
# workbook.save(filePath)
# 文件流的形式保存到内存
stream = io.BytesIO()
workbook.save(stream)
fileData = stream.getvalue()
stream.close()
# 读取保存的文件
# fileData = open(filePath, 'rb').read()
# app是Falsk实例 Flask(__name__)
response = app.make_response(fileData)
response.headers["Content-Disposition"] = 'attachment; filename=excel.xls'
response.headers["Content-Type"] = 'application/x-xlsx'
return response