https://simpleisbetterthancomplex.com/tutorial/2016/07/29/how-to-export-to-excel.html

Export data to excel is a common requirement on many web applications. Python makes everything easier. But, nevertheless, it is the kind of task I need to look for references whenever I have to implement.

I will give you two options in this tutorial: (1) export data to a .csv file using Python’s csv module; (2) export data to a .xls file using a third-party module named xlwt.

For both cases, consider we are exporting django.contrib.auth.models.User data.


Export Data to CSV File

Easiest way. No need to install dependencies, which is a great thing. Use it if you do not need any fancy formating.

views.py

import csv

from django.http import HttpResponse
from django.contrib.auth.models import User def export_users_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="users.csv"' writer = csv.writer(response)
writer.writerow(['Username', 'First name', 'Last name', 'Email address']) users = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
for user in users:
writer.writerow(user) return response

urls.py

import views

urlpatterns = [
...
url(r'^export/csv/$', views.export_users_csv, name='export_users_csv'),
]

template.html

<a href="{% url 'export_users_csv' %}">Export all users</a>

In the example above I used the values_list in the QuerySet for two reasons: First to query only the fields I needed to export, and second because it will return the data in a tuple instead of model instances. The writerowmethod expects a list/tuple.

Another way to do it would be:

writer.writerow([user.username, user.first_name, user.last_name, user.email, ])

Export Data to XLS File

Use it if you really need to export to a .xls file. You will be able to add formating as bold font, font size, define column size, etc.

First of all, install the xlwt module. The easiest way is to use pip.

pip install xlwt

views.py

import xlwt

from django.http import HttpResponse
from django.contrib.auth.models import User def export_users_xls(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="users.xls"' wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Users') # Sheet header, first row
row_num = 0 font_style = xlwt.XFStyle()
font_style.font.bold = True columns = ['Username', 'First name', 'Last name', 'Email address', ] for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows
font_style = xlwt.XFStyle() rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style) wb.save(response)
return response

urls.py

import views

urlpatterns = [
...
url(r'^export/xls/$', views.export_users_xls, name='export_users_xls'),
]

template.html

<a href="{% url 'export_users_xls' %}">Export all users</a>

Learn more about the xlwt module reading its official documentation.

How to Export to Excel的更多相关文章

  1. export to excel

    using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;npoi是重点. 定义一个exporttoe ...

  2. [Stephen]Export from Excel to ALM

    1.根据当前安装的ALM版本和Excel版本到https://hpln.hp.com/page/alm-excel-addin-page中对应的插件进行下载安装,安装时Excel需要关闭.安装成功后, ...

  3. 进阶-案例九: WD中实现export 到Excel,Doc,Txt.

    1.导出excel 文件代码 导出事件代码: METHOD onactionimport . *导出excel: DATA: lo_node TYPE REF TO if_wd_context_nod ...

  4. 笔记11 export to excel

    参考两篇博客:http://blog.csdn.net/zyming0815/article/details/5939104 http://blog.csdn.net/g710710/article/ ...

  5. We refined export to Excel for SharePoint

    http://sysmagazine.com/posts/208948/ http://sharepointwikipedia.blogspot.kr/2013/05/export-to-spread ...

  6. csharp: DataTable export to excel,word,csv etc

    http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...

  7. 笔记12 export to excel (NPOI)

    1:filestream 熟悉关于文件操作 ==>fs.Seek(0, SeekOrigin.Begin);//每次打开文件, ==>若果重写覆盖的话,必须先清空 fs.SetLength ...

  8. javascript export excel

    <input type="button" onclick="tableToExcel('tablename', 'name')" value=" ...

  9. [Rodbourn's Blog]How to export Excel plots to a vector image (EPS, EMF, SVG, etc.)

    This is a bit of a workaround, but it's the only way I know of to export an Excel plot into a vector ...

随机推荐

  1. js 自执行匿名函数(转载)

    自执行匿名函数: 常见格式:(function() { /* code */ })(); 解释:包围函数(function(){})的第一对括号向脚本返回未命名的函数,随后一对空括号立即执行返回的未命 ...

  2. express框架以及配置项

    以上命令会将 Express 框架安装在当前目录的 node_modules 目录中, node_modules 目录下会自动创建 express 目录.以下几个重要的模块是需要与 express 框 ...

  3. 构建工具 —— Groovy 与 Gradle

    1. Gradle Gradle 是一个基于 Groovy 的构建工具,使用 Groovy 来编写构建脚本,类似 maven,支持依赖管理和多项目创建. 相比 maven,更轻量: windows c ...

  4. 20165228 2017-2018-2 《Java程序设计》第8周学习总结

    20165228 2017-2018-2 <Java程序设计>第8周学习总结 教材学习内容总结 进程与线程的关系 多线程的运行机制 线程的四种状态:新建.运行.中断.死亡 使用Thread ...

  5. 关于Linux前后台进程切换

    前言: 当使用SSH远程登录服务器时,对于运行时间较长的程序(如Caffe的训练可能需要十几个小时), SSH可能会在很长时间后断掉,导致程序没运行完就中断了. 为了解决这个问题,需要将在服务器运行的 ...

  6. [LeetCode&Python] Problem 543. Diameter of Binary Tree

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  7. Xlua使用教程、攻略

    Xlua 使用指南 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享.心创新! ...

  8. day02编程语言介绍及python介绍

    编程语言介绍 机器语言:以二进制数为代码的编程语言,直接控制硬件运行 优点:执行效率非常快 缺点:以二进制数为编码编程,编程效率非常低下,掌握它需要深厚的硬件原理功底 汇编语言:将二进制编码用英文字符 ...

  9. XXS level1

    level1 (1)查看PHP源码,发现可以通过调用window,alert()完成任务 window.alert = function() { confirm("完成的不错!") ...

  10. CUDA学习

    CUDA(Compute Unified Device Architecture,统一计算架构)是由NVIDIA所推出的一种集成技术,是该公司对于GPGPU的正式名称.通过这个技术,用户可利用NVID ...