How To Export Excel Files in A Python - Django Application - ASSIST Software Romania
How To Export Excel Files in A Python - Django Application - ASSIST Software Romania
LIKE
39
Like
Python/Django application
Tweet
Share
(https://web.whatsapp.com/send?
July 25, 2016
text=https://assist-
FOLLOW
software.net/blog/how-
554
export-
Follow
excel-
les-
python-
django-
application)
CONTENTS
Introduction
Creating a working environment
How to serve a le for download
How to create an Excel le
How to add title and headers
How to write data
How to resize rows and columns
How to add formulas
How to add charts
Line charts
Column charts
Pie charts
Conclusions
(/team/irina-
popovici)
https://assist-software.net/blog/how-export-excel-files-python-django-application 1/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
Introduction
When creating a web management application, many clients require pages which display statistics. Usually
this feature comes along with the option to download the data in an Excel and/or PDF format. Therefore,
this tutorial will show you how to create an Excel document and make it available for download in a
Python/Django application.
Python (https://www.python.org/)2.7
Django (https://docs.djangoproject.com/en/1.8/) 1.8.2
XlsxWriter (https://xlsxwriter.readthedocs.org) 0.7.3
In order to expose the features brought by the XlsxWriter module, we created a simple Python/Django
application, which is available for download on Github (https://github.com/assist-software/python-django-
exporting- les). It consists of saving weather data for multiple towns. The user can add towns and weather
information through the Django Admin interface, which is generated automatically. The front page for this
website displays the current weather for the available towns. Moreover, the site contains a page that
presents the weather history data:
The user can lter the data by town, like in the above image, or select the default option which shows the
history for all the towns. You can notice that there is an “Excel Report” button, hence, that is the button
that will trigger the Excel le download.
The “WriteToExcel” function is responsible for creating the Excel le. It has two parameters:
weather_period, that represents the data after the ltering, we will utilize it for writing information in
the le; GET IN TOUCH (/CONTACT-U
town, its default value is None and is used in case the user selects a town for ltering.
https://assist-software.net/blog/how-export-excel-files-python-django-application 2/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
There are two options for writing the excel logic: either in the view or, like in this example, in a different le
(named “excel_utils.py”). The second option offers a more clean and modular code.
Creating styles which can be used later when we will be adding the data. For example, we may want a
bigger font size for the title, to make it to bold or we can add a color background for the headers:
?
1 title = workbook.add_format({
2 'bold': True,
3 'font_size': 14,
4 'align': 'center',
5 'valign': 'vcenter'
6 })
7 header = workbook.add_format({
8 'bg_color': '#F7F7F7',
9 'color': 'black',
10 'align': 'center',
11 'valign': 'top',
12 'border': 1
13 })
Adding a title that is written along more columns. In order to implement this you can use the
merge_range function, along with serving the columns, the text and the title style already de ned:
?
1 title_text = u"{0} {1}".format(ugettext("Weather History for"), town_text)
2 worksheet_s.merge_range('B2:H2', title_text, title)
Adding the headers which actually means writing text to some cells:
?
1 worksheet_s.write(4, 0, ugettext("No"), header)
2 worksheet_s.write(4, 1, ugettext("Town"), header)
3 worksheet_s.write(4, 3, ugettext(u"Max T. (℃)"), header)
4 # the rest of the headers from the HTML file
Please note that the code in this article will use ugettext function when de ning the texts. This is useful if
GET IN TOUCH (/CONTACT-U
you will add internationalization to the application. Moreover, keep in mind if you want to use unicode
characters (such as “℃” or diacritical marks) you have to add u before the string and also de ne the
di t th b i i f th l
https://assist-software.net/blog/how-export-excel-files-python-django-application 3/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
encoding at the beginning of the le:
?
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
But there is a problem, some texts do not t the columns, thus are not completely visible. The article will
tackle this issue in the “How to resize rows and columns” section.
?
1 for idx, data in enumerate(weather_data):
2 row = 5 + idx
3 worksheet_s.write_number(row, 0, idx + 1, cell_center)
4 worksheet_s.write_string(row, 1, data.town.name, cell)
5 worksheet_s.write(row, 2, data.date.strftime('%d/%m/%Y'), cell_center)
6 # the rest of the data
In order to avoid creating an additional variable that would be incremented on each loop, we can use the
python enumerate feature which automatically returns the index and the object from the list. You can
observe that the idx variable is used for writing the value in the Number column. Furthermore, it is used to
de ne a row variable, which along with a column value, determines where the data is written in the Excel
le.
In previous sections, there was an issue with the width of the rows. This problem can have multiple
solutions, depending on the desired results: GET IN TOUCH (/CONTACT-U
1. The columns can have a constant width. Suitable examples for this case are Date, Temperature, Wind and
https://assist-software.net/blog/how-export-excel-files-python-django-application 4/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
Precipitation columns. Thus, the code from below displays the change for Wind column. This line can be
added after or even before the loop that adds the data.
?
1 worksheet_s.set_column('G:G', 10)
Adding this setting to all the columns that suit this solution, modi es the Excel le as follows:
2. The columns can adapt their width according to the data that they contain, in this instance: Town and
Description. These values have a maximum length constraint in the database. Therefore, we can set a
column width according to the biggest length of all the data:
?
1 description_col_width = 10
2 # ...
3 for idx, data in enumerate(weather_data):
4 # ...
5 worksheet_s.write_string(row, 3, data.description, cell)
6 if len(data.description) > description_col_width:
7 description_col_width = len(data.description)
8 # ...
9 worksheet_s.set_column('D:D', description_col_width)
In this situation it is paramount to set the column options after the loop. Below is an image depicting how
the Excel le changed:
3. The column can have a constant width, but the row height can vary. The last column, Observations, is
where we can apply this condition. In this exercise, the width will be 25, meaning that we will consider that
one row cannot have more than 25 characters:
?
1 observations_col_width = 25
2 # ...
GET IN TOUCH (/CONTACT-U
3 for idx, data in enumerate(weather_data):
4 # ...
5 observations = data.observations.replace('\r', '')
https://assist-software.net/blog/how-export-excel-files-python-django-application 5/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
p ( )
6 worksheet_s.write_string(row, 9, observations, cell)
7 observations_rows = compute_rows(observations, observations_col_width)
8 worksheet_s.set_row(row, 15 * observations_rows)
9 # ...
10 worksheet_s.set_column('J:J', observations_col_width)
You can notice that the number of rows is computed using a function, named “compute_rows” (its
parameters are the text and the column width):
?
1 def compute_rows(text, width):
2 if len(text) < width:
3 return 1
4 phrases = text.replace('\r', '').split('\n')
5
6 rows = 0
7 for phrase in phrases:
8 if len(phrase) < width:
9 rows = rows + 1
10 else:
11 words = phrase.split(' ')
12 temp = ''
13 for idx, word in enumerate(words):
14 temp = temp + word + ' '
15 # check if column width exceeded
16 if len(temp) > width:
17 rows = rows + 1
18 temp = '' + word + ' '
19 # check if it is not the last word
20 if idx == len(words) - 1 and len(temp) > 0:
21 rows = rows + 1
22 return rows
As you can observe, there are cells that have extra rows. This happens due to the fact that the letters do
not have the same width; so even though the number of characters exceeds the set maximum, the text ts
in less than the expected space. This solution only simulates an Auto Fit option. As a result, some extra
rows may appear when the text has a large number of characters.
The formula is added using the write_formula functions which has 5 parameters, three of them are
mandatory: row, column, a string de ning the formula and the other two are optional: cell style and the
computed value (it is useful to add this because when opening the le with an Excel Viewer it will display 0
instead of the expected result).
The le now has another row of data at the end of the table:
Line charts
In this case, we could use a line chart in order to show temperature data for the towns along a certain
amount of time.
Afterwards we have to add the data on the “Charts Data” sheet and read it in order to add series to the
chart:
?
1 line_chart.add_series({
2 'categories': '=Chart Data!$A1:$A${0}'.format(len(dates)),
3 'values': '=Chart Data!${0}${1}:${0}${2}'
4 .format(letter_max_t, 1, len(data)),
5 'marker': {'type': 'square'},
6 'name': u"{0} {1}".format(ugettext("Max T."), t.name)
7 })
The code from above can be written in a loop which would add this line for all the towns. Also, you can
notice the fact that the values for categories and values will be read from the “Chart Data” sheet.
setting a title
?
1 line_chart.set_title({'name': ugettext("Maximum and Minimum Temperatures")})
adding options for the x axis, for instance, the labels can contain strings instead of numbers: GET IN TOUCH (/CONTACT-U
?
1 line_chart.set_x_axis({
https://assist-software.net/blog/how-export-excel-files-python-django-application 7/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
_ _ _ ({
2 'text_axis': True,
3 'date_axis': False
4 })
adding options for the y axis, for example, we can add measuring units for the temperature values:
?
1 line_chart.set_y_axis({
2 'num_format': u'## ℃'
3 })
including the chart on the “Charts” Sheet, where we have the option to change the scale. This can be
considered as the last step.
?
1 worksheet_c.insert_chart('B2', line_chart, {'x_scale': 2, 'y_scale': 1})
Column charts
In order to expose the usability of the column charts we are going to display the maximum and minimum
value for wind speed for each of the available towns.
The work ow is identical to the previous chart, however, when creating the new chart object we have to
change its type:
?
1 bar_chart = workbook.add_chart({'type': 'column'})
Next step is to make aggregations on the data, add it onto the data sheet and then create the series. For
example the series for the maximum values is:
1 bar_chart.add_series({
2 'name': 'Max Speed', GET IN TOUCH (/CONTACT-U
3 'values': '=Chart Data!${0}${1}:${0}${2}'
4 .format(chr(ord('A') + cell_index + 1), 1, len(towns)),
5 'categories': '=Chart Data!${0}${1}:${0}${2}'
https://assist-software.net/blog/how-export-excel-files-python-django-application 8/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
g { } { } { } { }
6 .format(chr(ord('A') + cell_index), 1, len(towns)),
7 'data_labels': {'value': True, 'num_format': u'#0 "km/h"'}
8 })
You can notice that we added some formatting to the data labels as well. After adding the title and inserting
it into the charts sheet, we can observe the result:
Pie charts
This time, we will create a pie chart object, which present the percentage of hot, warm and cold days:
?
1 pie_chart = workbook.add_chart({'type': 'pie'})
Like in the previous examples, we have to aggregate the data, write it in the Excel and add the
corresponding series:
?
1 pie_chart.add_series({
2 'name': ugettext('Temperature statistics'),
3 'values': '=Chart Data!${0}${1}:${0}${2}'
4 .format(chr(ord('A') + cell_index), 1, 3),
5 'categories': '=Chart Data!${0}${1}:${0}${2}'
6 .format(chr(ord('A') + cell_index + 1), 1, 3),
7 'data_labels': {'percentage': True}
8 })
The main difference from the other charts is that the values are automatically calculated as percentages.
After inserting the chart on the worksheet we have the following result:
Conclusions
In conclusion, when creating a Python/Django application that requires to export Excel les, XlsxWriter
(https://xlsxwriter.readthedocs.org) is a very useful module. You can access the of cial docs for this module
where you will nd further features and options to add.
Moreover, you can access the whole code for this application on Github (https://github.com/assist-
software/python-django-exporting- les). Hopefully it will help many developers learn how to exportGET IN TOUCH (/CONTACT-U
Excel
les in a Python/Django properly.
https://assist-software.net/blog/how-export-excel-files-python-django-application 9/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
In this article, the main subject was creating an Excel le in a Python/Django application. In a future article
the attention will be drawn to PDF, another way to export data.
* The Excel les from the screenshots were opened with LibreOf ce
UPDATE: In this article, the main subject was creating an Excel le in a Python/Django application. If you
want to export PDF les check this article written by our colleague Petru (https://assist-
software.net/blog/how-create-pdf- les-python-django-application-using-reportlab).
(https://twitter.com/intent/tweet?
text=How to
export Excel
(https://www.facebook.com/sharer/sharer.php?
PythonDjango (https://plus.google.com/share?
(http://www.linkedin.com/shareArticle?
u=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fassist-
application&url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fassist-
url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fassist-
mini=true&url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fassist-
software.net%2Fblog%2Fhow-
software.net%2Fblog%2Fhow-
software.net%2Fblog%2Fhow-
software.net%2Fblog%2Fhow-
Add a comment...
German Villacorta
no funciono, gracias por nada
Like · Reply · 2 · 2y
German Villacorta
por favor ayudame
Like · Reply · 1 · 2y
Irina Popovici
German Villacorta Hi, please give us more details on your problem. Thank you!
Like · Reply · 1 · 2y
German Villacorta
Irina Popovici It already worked, thanks for your help!
Like · Reply · 2 · 2y
Irina Popovici
We got an interesting question from Samuel:
GET IN TOUCH (/CONTACT-U
Hello. Am trying to make reports for data in models for use by the staff. Which is the best approach to use in
this?
https://assist-software.net/blog/how-export-excel-files-python-django-application 10/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
Like · Reply · 2 · 2y
Irina Popovici
Hi Samuel,
Taking into consideration that you want those reports to be available only for staff members, I
recommend that when you create the view for exporting the files you also add a decorator.
In that decorator you can check if that user is staff, otherwise you should redirect that user to a
different page and display a "Permission denied" message.
I would also suggest that you display the link/button only for staff by checking the user in the
template.… See More
Like · Reply · 1 · 2y
Solomon Nsubuga
Great article, just the knowledge I needed to complete an assignment. Thank you so much!!!!!!
Like · Reply · 1 · 1y
I have a question:
View.py:
def envrec(request):
if request.method == 'POST':
form = BuscarForm(request.POST)
result_list = []
if form.is_valid():… See More
Like · Reply · 1 · 1y
Arkady Aristov
Thank you! Very usefull article.
Like · Reply · 1 · 1y
Arif Shaikh
very nice
Like · Reply · 1 · 1y
Izak Hey
Thank you for this tutorial! Does it still work now, I got a lot of issues with xlsWriter:
'Worksheet' object has no attribute '_xml_number_element'
unsupported operand type(s) for -: 'User' and 'User'
...
Like · Reply · 1 · 1y
Izak Hey
That would be awesome if it could be update with the latest version of Django
Like · Reply · 1 · 1y
Eduardo Lucas
Congrats, great job!
Like · Reply · 1 · 1y
Ishu
I clicked on the link GitHub to download the source files. The folder is available in C drive.. In the windows
command prompt, C:\django-excel-import-master> python manange.py runserver ...... gives me a error....
from configurations.mangement import execute_from_command_line Import error: No module named
'configurations'
Like · Reply · 1 · 1y
Sridhar Chary
import xlsxwriter gives me like this msg GET IN TOUCH (/CONTACT-U
Sebastien Jarrin
Hi, I did everything, it seems to be good!! What can i do with no data for today and no weather history and
no towns. How can I put informations ? Thanks in advanced !!
Like · Reply · 35w
Shivangi Roy
Very Impressive Python tutorial. The content seems to be pretty exhaustive and excellent and will definitely
help in learning Python course. I'm also a learner taken up Pyhton training and I think your content has
cleared some concepts of mine. While browsing for Python tutorials on YouTube i found this fantastic video
on Python. Do check it out if you are interested to know more.https://www.youtube.com/watch?
v=e9p0_NB3WrM
Like · Reply · 21w
READING NEXT
TA G S
https://assist-software.net/blog/how-export-excel-files-python-django-application 12/13
6/10/2018 How to export Excel files in a Python/Django application | ASSIST Software Romania
Drop us a line. We’d love to hear from you and see how we can help in solving your digital
challenges. As one of the best software outsourcing companies in Romania, Eastern Europe,
Europe and the world really, we are sure we can ASSIST.
© ASSIST SOFTWARE 1992 - 2018. ALL RIGHTS RESERVED. Terms of Use (/terms-of-use)
https://assist-software.net/blog/how-export-excel-files-python-django-application 13/13