使用
response.write(codecs.BOM_UTF8)
示例:导出数据到CSV
def export_csv(request):
"""测试导出功能"""
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
response.write(codecs.BOM_UTF8)
writer = csv.writer(response)
writer.writerow(['序号', '姓名', '性别', '年龄'])
writer.writerow(['1', '张三', '男', '18'])
return response
示例:从模型层中导出数据到CSV
def export_csv(request):
"""测试导出功能"""
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
response.write(codecs.BOM_UTF8)
writer = csv.writer(response)
queryset = models.Domain.objects.values('domain_name', 'node_name')
writer.writerow(['域名', '节点名称'])
for item in queryset:
writer.writerow(item.values())
return response
相关文档
利用 Django 输出 CSV
https://docs.djangoproject.com/zh-hans/3.0/howto/outputting-csv/