使用

  1. response.write(codecs.BOM_UTF8)

示例:导出数据到CSV

  1. def export_csv(request):
  2. """测试导出功能"""
  3. response = HttpResponse(content_type='text/csv')
  4. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  5. response.write(codecs.BOM_UTF8)
  6. writer = csv.writer(response)
  7. writer.writerow(['序号', '姓名', '性别', '年龄'])
  8. writer.writerow(['1', '张三', '男', '18'])
  9. return response

示例:从模型层中导出数据到CSV

  1. def export_csv(request):
  2. """测试导出功能"""
  3. response = HttpResponse(content_type='text/csv')
  4. response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
  5. response.write(codecs.BOM_UTF8)
  6. writer = csv.writer(response)
  7. queryset = models.Domain.objects.values('domain_name', 'node_name')
  8. writer.writerow(['域名', '节点名称'])
  9. for item in queryset:
  10. writer.writerow(item.values())
  11. return response

相关文档

利用 Django 输出 CSV
https://docs.djangoproject.com/zh-hans/3.0/howto/outputting-csv/