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. FutureTask

    因为实现了runnable接口,所以重写了run方法 Future接口如果用在多线程中,实现类一般是有一个volatile的属性,用来标志状态,比如state,如果事情做完了,那么会设置state为成 ...

  2. shiro学习笔记(四) ini配置以及加解密

    INI配置 从之前的Shiro架构图可以看出,Shiro是从根对象SecurityManager进行身份验证和授权的:也就是所有操作都是自它开始的,这个对象是线程安全且真个应用只需要一个即可,因此Sh ...

  3. shell脚本实例-mysql多机部署

    今天我给大家分享shell 安装mysql 多机部署的实例,本次实验是基于各个主机的公钥已经配置好了,如果还不会推送公钥的同学,可以看看我以前写的文章,那里面有写推公钥的实例,mysql 多机部署一般 ...

  4. ChinaCock界面控件介绍-TCCYearMonthSelector

    Delphi原生控件支持日期的选择,但对于只选择年月的情况,则没有好的实现.TCCYearMonthSelector正是为解决这个问题而产生的.看看运行效果图: 用法一如即往的简单,这是一个不可视控件 ...

  5. ie 折腾计(浏览器兼容性)

    常见问题 IE:6.0,IE7.0,IE8.0之间的兼容独立说明 /*用于展示标签*/ <div class="jrx"></div> <style ...

  6. LINUX内核完全注释

    学习教材:LINUX内核完全注释,内核版本0.11,修正版V3.0 赵炯编著 参考教材:UNIX操作系统设计--M. J. Bach, programming the 80x86  --John H. ...

  7. python day 16作业

    day18天作业及默写1,完成下列功能: 1.1创建一个人类Person,再类中创建3个静态变量(静态字段) animal = '高级动物' soup = '有灵魂' language = '语言' ...

  8. 【转载】 强化学习(七)时序差分离线控制算法Q-Learning

    原文地址: https://www.cnblogs.com/pinard/p/9669263.html ------------------------------------------------ ...

  9. 集合框架 ArrayList LinkedList(待续)

    ArrayList中存储的元素的内存空间是连续的, LinkedList内存空间不是连续的 集合对象不能被序列化到硬盘中 http://blog.csdn.net/eson_15/article/de ...

  10. MySQL安装配置错误\日常使用错误

    1.出现报错---应用程序无法正常启动0xc000007b 安装direct 9.0 安装vc++ 2005 安装vc++ 2008 安装vc++ 2012(x64和x86都要装) 安装 .NET4. ...