How to Export to Excel
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 writerow
method 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的更多相关文章
- export to excel
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;npoi是重点. 定义一个exporttoe ...
- [Stephen]Export from Excel to ALM
1.根据当前安装的ALM版本和Excel版本到https://hpln.hp.com/page/alm-excel-addin-page中对应的插件进行下载安装,安装时Excel需要关闭.安装成功后, ...
- 进阶-案例九: WD中实现export 到Excel,Doc,Txt.
1.导出excel 文件代码 导出事件代码: METHOD onactionimport . *导出excel: DATA: lo_node TYPE REF TO if_wd_context_nod ...
- 笔记11 export to excel
参考两篇博客:http://blog.csdn.net/zyming0815/article/details/5939104 http://blog.csdn.net/g710710/article/ ...
- We refined export to Excel for SharePoint
http://sysmagazine.com/posts/208948/ http://sharepointwikipedia.blogspot.kr/2013/05/export-to-spread ...
- csharp: DataTable export to excel,word,csv etc
http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...
- 笔记12 export to excel (NPOI)
1:filestream 熟悉关于文件操作 ==>fs.Seek(0, SeekOrigin.Begin);//每次打开文件, ==>若果重写覆盖的话,必须先清空 fs.SetLength ...
- javascript export excel
<input type="button" onclick="tableToExcel('tablename', 'name')" value=" ...
- [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 ...
随机推荐
- Linux文件系统命令 ls
名称:ls 功能:查看文件列表 renjg@renjg-HP-Compaq-Pro--MT:~$ ls add-on.yaml Desktop examples.desktop meta-gnome3 ...
- el-container 实践上的布局问题
当自己利用element-ui上面的例子来实现整体布局的时候, 就是自己分开成单独的vue组件时,发现布局是不对的,效果是这样的: 代码是这样的,代码一模一样,只是拆开了各个组件,如下图: 后来发现是 ...
- Android SurfaceView内容获取
Android SurfaceView内容获取 这几天在做一个Android的小项目,项目中需要使用到SurfaceView来显示相机捕获的内容,同时还有一个SurfaceView用于绘制一些辅助线, ...
- centos /data目录扩容
/data盘被日志撑死了,必须扩容 有一块现成的100G的/dev/sdb盘,但是mount到了/data/test目录下,而且还有应用程序在上面进行读写操作 1.先查看哪些应用程序 在占用磁盘 #f ...
- Oracle使用exp和imp导出、导入数据
===========导出============ exp 用户名/密码@服务器(localhost) file=文件路径.dmp owner=(用户名) ===========导入========= ...
- django面试七
Dango model 几种继承形式抽共享继承不能等实例化,抽象方法必须在子类中实现,Django不对其建立对应的表.class Animal(models.Model): name = models ...
- os.path和sys.path的区别
os.path是module,包含了各种处理长文件名(路径名)的函数. sys.path是由目录名构成的列表,python从中查找扩展模块(python源模块)编译模块,或者二进制扩展),启动pyth ...
- ubatu 安装nodejs npm liveserver
更新ubuntu软件源 sudo apt-get update sudo apt-get install -y python-software-properties software-properti ...
- 设置环境下文本格式为UTF-8
1.在页面创建一个template.txt文本格式,默认是ANSI,将其格式改为UTF-8 2.将template.txt丢到C:\Windows\ShellNew文件夹里面 3.打开命令行工具win ...
- Java应用集群下的定时任务处理方案(mysql)
Java应用集群下的定时任务处理方案(mysql) 因为自己有csdn和博客园两个博客, 所以两边都会发一下. csdn地址: http://blog.csdn.net/u012881584/ar ...