以csv形式
# 从数据库查询数据
data_list = User.objects.all()
# 定义返回对象
response = HttpResponse()
# 给返回对象定义解析类型
response['Content-Type'] = 'csv'
# 声明一个csv的响应
response['Content-Disposition'] = 'attachment;filename="data.csv"'
# csv的响应编码格式声明
response.write(codecs.BOM_UTF8)
# 把响应设置成文件句柄
writer_obj = csv.writer(response)
# 先写入表格头
writer_obj.writerow(["姓名", "年龄", "地址"])
# 写入数据
for info in data_list:
writer_obj.writerow([info.name, info.age, info.address])
return response
# 详细讲解 https://www.cnblogs.com/zhzhlong/p/9310106.html
以xls形式
products = Product.objects.filter(is_delete=False).all()
serializer = ProductSerializer(products, many=True)
http_response = HttpResponse()
output = BytesIO()
work_book = xlwt.Workbook(encoding="utf-8")
work_sheet = work_book.add_sheet("1")
table_title = [
'商品id', '用户id', '用户名',
]
for table_index, table_name in enumerate(table_title):
work_sheet.write(0, table_index, table_name)
for index, data in enumerate(serializer.data):
row_data = [
str(data['id']), str(data['user']), data['username']
]
for i, cell_data in enumerate(row_data):
work_sheet.write(index + 1, i, cell_data)
work_book.save(output)
output.seek(0)
http_response["Content-Type"] = "application/octet-stream"
filename = datetime.now().strftime("%Y%m%d%H%M%S")
http_response["Content-Disposition"] = f'filename="{filename}.xls"'
http_response.write(output.getvalue())
return http_response
不通过浏览器下载,直接生成
filename = '{}.xls'.format(datetime.now().strftime("%Y%m%d%H%M%S"))
work_book.save(output)
output.seek(0)
work_book.save(filename)