Expert , professional,personal and affordable web Development framework is one and only DJANGO ( Python web development framework )
Wednesday, April 1, 2015
How to Export Your Data as CSV, XLS, or XLSX in Django ?
How to Export Your
Data as CSV, XLS, or XLSX
There are times,
when you need to export the data from your database to different
formats. For example, you want to create some diagrams in Office
program for a presentation. In this post I will show you how to
create admin actions which export selected items as files for a
spreadsheet application (like MS Excel, OpenOffice Calc, LibreOffice
Calc, Gnumeric, or Numbers). I will cover the mostly used formats:
Comma Separated Values (CSV), Binary Excel (XLS), and Office Open XML
First of all, have a
look at the model we will be dealing with. It's a simple model with
title, description, and - of course - the id.
admininstration options, we'll define three admin actions:
export_csv, export_xls, and export_xlsx.
from models import
# ... export
functions will go here ...
[export_csv, export_xls, export_xlsx]
Now let's create
functions for each of those actions!
CSV is the most
common import and export format for spreadsheets and databases. It's
a textual format which one could easily create or parse himself, but
there is also a python built-in library csv for handy data
response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel
needs it to open UTF-8 file properly)
for obj in
= u"Export CSV"
As you can see,
HttpResponse is a file-like object and we used it to write data to.
Excel Binary File
XLS is the main
spreadsheet format which holds data in worksheets, charts, and
macros. We are going to use xlwt library to create a spreadsheet.
There is analogous library xlrd to read XLS files. Note, that this
format allows to have only 256 columns.
Here we created one
worksheet, filled it with data, marked the first row in bold, and
made the lines in the other cells wrapped. Also we set the width for
each column. We'll do the same in the next format too.
Office Open XML
XLSX (a.k.a. OOXML
or OpenXML) is a zipped, XML-based file format developed by
Microsoft. It is fully supported by Microsoft Office 2007 and newer
versions. OpenOffice 4.0, for example, can only read it. There is a
python library openpyxl for reading and writing those files. This
format is great when you need more than 256 columns and text
So whenever you need
to get your Django project data to some spreadsheet application,
there are several ways to do that. If you are planning to import the
data to some other database, CSV is probably the best, as it is
simple, straightforward, and requires no third-party libraries.
However, if you need your data with nice formatting and maybe some
statistical formulas, you should export XLS or XLSX format. The
maximum amount of columns in XLS format is limited to 256, whereas
XLSX format allows more columns, but is not fully supported by all