标签:excel 回流 src 继承 恶心 def 中文 就会 chm
wb = Workbook() ws = wb.active # 首行列名写入excel for i, t in enumerate(title): ws.cell(row=1, column=(i + 1)).value = t[1] # 数据部分写入excel title_fields = [t[0] for t in title] for i, _data in enumerate(data): one_row = [_data[t] for t in title_fields] for j, d in enumerate(one_row): ws.cell(row=(i + 2), column=(j + 1)).value = d
wb.save(filename)
sio = BytesIO()
wb.save(sio)
response = Response() response.headers.add("Content-Type", "application/vnd.ms-excel") response.headers.add(‘Content-Disposition‘, ‘attachment‘, filename=filename.encode("utf-8").decode("latin1")) sio.seek(0) response.data = sio.getvalue() return response
from flask import Flask from excel import generate_excel app = Flask(__name__) @app.route(‘/‘) def hello_world(): return ‘Hello World!‘ @app.route(‘/excel‘) def download(): data = [ {"key1": 1, "key2": 2, "key3": 3}, {"key1": 11, "key2": 22, "key3": 33}, {"key1": 111, "key2": 222, "key3": 333}, {"key1": 1111, "key2": 2222, "key3": 3333}, {"key1": 11111, "key2": 22222, "key3": 33333}, ] title = [("key1", "第一列"), ("key2", "第二列"), ("key3", "第三列")] filename = "测试Excel.xlsx" return generate_excel(title, data, filename) if __name__ == ‘__main__‘: app.run()
from io import BytesIO from openpyxl import Workbook from flask import Response def generate_excel(title, data, filename): wb = Workbook() ws = wb.active # 首行列名写入excel for i, t in enumerate(title): ws.cell(row=1, column=(i + 1)).value = t[1] # 数据部分写入excel title_fields = [t[0] for t in title] for i, _data in enumerate(data): one_row = [_data[t] for t in title_fields] for j, d in enumerate(one_row): ws.cell(row=(i + 2), column=(j + 1)).value = d # 传给save函数的不是保存文件名,而是BytesIO流 sio = BytesIO() wb.save(sio) response = Response() response.headers.add("Content-Type", "application/vnd.ms-excel") response.headers.add(‘Content-Disposition‘, ‘attachment‘, filename=filename.encode("utf-8").decode("latin1")) sio.seek(0) response.data = sio.getvalue() return response
2、Django版本
from django.http import HttpResponse from django.utils.encoding import escape_uri_path # ...从生成excel到wb.save(sio)都是一样的 response = HttpResponse() response["Content-Type"] = "application/vnd.ms-excel" response["Content-Disposition"] = "attachment; filename*=UTF-8‘‘%s" % escape_uri_path(filename) # 保存流 sio.seek(0) response.write(sio.getvalue()) return response
标签:excel 回流 src 继承 恶心 def 中文 就会 chm
原文地址:https://www.cnblogs.com/anpengapple/p/13195881.html