django返回excel
django后台返回excel表
方法一(不推荐)
思路:先根据条件从数据库查找data,再把data生成excel表,再把excel表返回(FileResponse)
步骤:
-
data:利用django.forms.model_to_dict 把数据转化成dict,注意,ImageField无法转化
from django.forms import model_to_dict user_infos = UserInfo.objects.filter(**kwargs) data = list(map(lambda x: model_to_dict(x, exclude=["avatr"]), user_infos)
- excel:使用xlsxwriter库根据data生成excel表
- FileResponse:使用 django.http.FileResponse 返回
from django.http import FIleResponse with open("./excel/userinfos.xlsx", "rb") as f: res = FileResponse(f) res["Content-Type"] = "application/octet-stream" res["Content-Disposition"] = 'filename="userinfs.xlsx"' return res
缺点:每次针对不同的请求要生成不同的excel文件
方法二(推荐)
思路:先查出数据data,再在内存中写一个excel文件,再返回出去,这样就省了一步
步骤:
- data:和上面一样
- excel+HttpResponse:在内存中写excel
from django.http import HttpResponse from io import BytesIO import xlsxwriter x_io = BytesIO() work_book = xlsxwriter.WorkBook(x_io) work_sheet = work_book.add_sheet("excel-1") ... ... ... work_book.close() res = HttpResponse() res["Content-Type"] = "application/octet-stream" res["Content-Disposition"] = 'filename="userinfos.xlsx"' res.write(x_io.getvalue()) return res
其他:与上面的比较就是不用再去写一个excel文件了,也不用过后再删除了。
xlsxwriter 的使用方法
pip install xlsxwriter
pip install xlsxwriter import xlswriter # 注意这里与上面用BytesIO的区别 work_book = xlsxwriter.workbook.WorkBook("./excel/user_data.xlsx") work_sheet = work_book.add_sheet("excel-1") data = [{"a":1, "b": 2}, {"a":22, "b":11}, {"a":54, "b":99}...] keys = dict(data[0].keys()) keys.sort() row, col = 0, 0 # 写头 for k in keys: # 意思是:在row行,col列,写了一个k work_sheet.write(row, col, k) col += 1 # 写内容 row, col = 1, 0 for temp in data: for k in keys: work_sheet.write(row, col, temp[k]) col += 1 row += 1 col = 0 # work_book.close() # 这样就写了一个名为 user_data.xlsx 的文件了
本文来自博客园,作者:长情不羁的五年,转载请注明原文链接:https://www.cnblogs.com/grlend/p/16191081.html

浙公网安备 33010602011771号