Django-Excel: Excel File Handling Guide
Django-Excel: Excel File Handling Guide
Release 0.0.10
2 Installation 5
3 Setup 7
7 Tutorial 15
7.1 Handle excel file upload and download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7.2 Handle data import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.3 Handle data export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
7.4 Render an excel-alike html in a browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
7.5 Handle custom data export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
7.6 Visualize your data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
9 API Reference 31
10 Response methods 35
Index 39
i
ii
django-excel Documentation, Release 0.0.10
Author C.W.
Source code http://github.com/pyexcel-webwares/django-excel.git
Issues http://github.com/pyexcel-webwares/django-excel/issues
License New BSD License
Released 0.0.10
Generated Nov 10, 2020
Here is a typical conversation between the developer and the user:
django-excel is based on pyexcel and makes it easy to consume/produce information stored in excel files over HTTP
protocol as well as on file system. This library can turn the excel data into a list of lists, a list of records(dictionaries),
dictionaries of lists. And vice versa. Hence it lets you focus on data in Django based web development, instead of file
formats.
The idea originated from the common usability problem: when an excel file driven web application is delivered for
non-developer users (ie: team assistant, human resource administrator etc). The fact is that not everyone knows (or
cares) about the differences between various excel formats: csv, xls, xlsx are all the same to them. Instead of training
those users about file formats, this library helps web developers to handle most of the excel file formats by providing
a common programming interface. To add a specific excel file format type to you application, all you need is to install
an extra pyexcel plugin. Hence no code changes to your application and no issues with excel file formats any more.
Looking at the community, this library and its associated ones try to become a small and easy to install alternative to
Pandas.
The highlighted features are:
1. excel data import into and export from databases
2. turn uploaded excel file directly into Python data structure
3. pass Python data structures as an excel file download
4. provide data persistence as an excel file in server side
5. supports csv, tsv, csvz, tsvz by default and other formats are supported via the following plugins:
Contents 1
django-excel Documentation, Release 0.0.10
2 Contents
CHAPTER 1
Since 2020, all pyexcel-io plugins have dropped the support for python version lower than 3.6. If you want to use any
python verions, please use pyexcel-io and its plugins version lower than 0.6.0.
Except csv files, xls, xlsx and ods files are a zip of a folder containing a lot of xml files
The dedicated readers for excel files can stream read
In order to manage the list of plugins installed, you need to use pip to add or remove a plugin. When you use virtualenv,
you can have different plugins per virtual environment. In the situation where you have multiple plugins that does
the same thing in your environment, you need to tell pyexcel which plugin to use per function call. For example,
pyexcel-ods and pyexcel-odsr, and you want to get_array to use pyexcel-odsr. You need to append get_array(. . . ,
library=’pyexcel-odsr’).
This library makes information processing involving various excel files as easy as processing array, dictionary when
processing file upload/download, data import into and export from SQL databases, information analysis and persis-
tence. It uses pyexcel and its plugins:
1. to provide one uniform programming interface to handle csv, tsv, xls, xlsx, xlsm and ods formats.
3
django-excel Documentation, Release 0.0.10
2. to provide one-stop utility to import the data in uploaded file into a database and to export tables in a database
as excel files for file download.
3. to provide the same interface for information persistence at server side: saving a uploaded excel file to and
loading a saved excel file from file system.
Given the existence of pyexcel, what is the reason for django-excel? 1. Speedy file uploads. django-excel help
you access the uploaded excel file directly using ExcelMemoryFileUploadHandler and TemporaryExcelFileUpload-
Handler. MemoryFileUploadHandler holds the uploaded file in memory and django-excel reads the excel data from
this memory buffer without caching it onto file system. Meanwhile, TemporaryExcelFileUploadHandler holds the
uploaded file in file system and django-excel reads directly from this stream-to-file without extra function calls. 2.
Import excel data into database. django-excel uses bulk_insert to import your excel data into your django Model,
which is very efficient.
Installation
Installation of individual plugins , please refer to individual plugin page. For example, if you need xlsx file support,
please install pyexcel-xlsx:
Contrary to Django’s philosophy of ‘battery included’, django-excel does not come with all batteries due to the size of
the dependency(xlwt, openpyxl, odfpy). Hence, Django developer is left with the choice to install and load the excel
file formats.
5
django-excel Documentation, Release 0.0.10
6 Chapter 2. Installation
CHAPTER 3
Setup
FILE_UPLOAD_HANDLERS = ("django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler")
7
django-excel Documentation, Release 0.0.10
8 Chapter 3. Setup
CHAPTER 4
9
django-excel Documentation, Release 0.0.10
If your company has embedded pyexcel and its components into a revenue generating product, please support me on
github, patreon or bounty source to maintain the project and develop it further.
If you are an individual, you are welcome to support me too and for however long you feel like. As my backer, you
will receive early access to pyexcel related contents.
And your issues will get prioritized if you would like to become my patreon as pyexcel pro user.
With your financial support, I will be able to invest a little bit more time in coding, documentation and writing
interesting posts.
11
django-excel Documentation, Release 0.0.10
The example application understands csv, tsv and its zipped variants: csvz and tsvz. If you would like to expand the
list of supported excel file formats (see A list of file formats supported by external plugins) for your own application,
you could install one or all of the following:
Warning: If you are using pyexcel <=0.2.1, you still need to import each plugin manually, e.g. import pyex-
cel.ext.xls and Your IDE or pyflakes may highlight it as un-used but it is used. The registration of the extra file
format support happens when the import action is performed
13
django-excel Documentation, Release 0.0.10
Tutorial
In order to dive in django-excel and get hands-on experience quickly, the test application for django-excel will be
introduced here. So, it is advisable that you should check out the code from github
The test application is written according to Part 1, Part 2 and Part 3 of django tutorial. If you should wonder how the
test application was written, please visit django documentation and come back.
Once you have the code, please change to django-excel directory and then install all dependencies:
$ cd django-excel
$ pip install -r requirements.txt
$ pip install -r tests/requirements.txt
You have 9 unapplied migration(s). Your project may not work properly until you apply
˓→the migrations for app(s): admin, auth, contenttypes.
Note: The 9 unapplied migration(s) were ignored because migrations are out of scope in this tutorial.
15
django-excel Documentation, Release 0.0.10
This example shows how to process uploaded excel file and how to make data download as an excel file. Open your
browser and visit http://localhost:8000/polls/, you shall see this upload form:
Choose an excel sheet, for example an xls file, and press “Submit”. You will get a csv file for download.
Please open the file polls/views.py and focus on the following code section:
16 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
UploadFileForm is html widget for file upload form in the html page. Then look down at filehandle. It is an instance
of either ExcelInMemoryUploadedFile or TemporaryUploadedExcelFile, which inherit ExcelMixin and hence have a
list of conversion methods to call, such as get_sheet, get_array, etc.
For the response, make_response() converts pyexcel.Sheet instance obtained via get_sheet() into a csv
file for download.
Please feel free to change those functions according to the mapping table.
This example shows how to import uploaded excel file into django models. We are going to import sample-data.xls
into the following data models:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
slug = models.CharField(max_length=10, unique=True,
default="question")
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Note: Except the added “slug” field, Question and Choice are copied from Django tutorial part 1.
Note: Please also pay attention to ‘choice’ sheet. There exists an arbitrary column: “Noise”, which exists to show
case skipping column feature using mapdicts later.
Please visit this link http://localhost:8000/polls/import/, you shall see this upload form:
Please then select sample-data.xls and upload. And you get the following excel-alike table in response to confirm all
were imported.
18 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
Note: pyexcel-handsontable along with pyexcel v0.5.0 brings excel-alie table rendering feature. Let me explain how
this view is done a few paragraphs later.
Then visit the admin page http://localhost:8000/admin/polls/question, you shall see questions have been populated:
Note: The admin user credentials are: user name: admin, password: admin
You may use admin interface to delete all those objects and try again.
Now please open polls/views.py and focus on this part of code:
def import_data(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
def choice_func(row):
q = Question.objects.filter(slug=row[0])[0]
row[0] = q
return row
if form.is_valid():
request.FILES["file"].save_book_to_database(
models=[Question, Choice],
initializers=[None, choice_func],
mapdicts=[
["question_text", "pub_date", "slug"],
{"Question": "question", "Choice": "choice_text", "Votes": "votes
˓→ "},
],
)
return redirect("handson_view")
else:
return HttpResponseBadRequest()
The star is save_book_to_database(). The parameter models should be a list of django models. initializers
is a list of initialization functions for each model. In the example, we do not have init function for Question so ‘None’
is given and choice_func is given to Choice. mapdicts is a list of column names for each model and the member of
the mapdicts can be a dictionary:
20 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
{
"Question Text": "question_text",
"Publish Date": "pub_date",
"Unique Identifier": "slug"
}
As a dictionary, it can be used to skip columns in the incoming sheets. For example, ‘Noise’ column is skipped because
it was not mentioned in the mapdict.
The custom initialization function is needed when the data from the excel sheet needs translation before data import.
For example, Choice has a foreign key to Question. When choice data are to be imported, “Question” column needs
to be translated to a question instance. In our example, “Question” column in “Sheet 2” contains the values appeared
in “Unique Identifier” column in “Sheet 1”.
This section shows how to export the data in your models as an excel file. After you have completed the previous
section, you can visit http://localhost:8000/polls/export/book and you shall get a file download dialog:
Please save and open it. You shall see these data in your window:
make_response_from_tables() does all what is needed: read out the data, convert them into xls and give it
the browser. And what you need to do is to give a list of models to be exported and a file type. As you have noticed,
you can visit http://localhost:8000/polls/export/sheet and will get Question exported as a single sheet file.
In previous section, you have seen the rendering of the excel-alike table. First of all, the credits goes to handsontable
developers. pyexcel-handsontable as renderer plugin to pyexcel v0.5.0 bring it to pyexcel developers.
Here is how it is done. Simply put in ‘handsontable.html’ instead of ‘xls’ as file type.
return excel.make_response_from_tables(
[Question, Choice], "handsontable.html"
)
It is understood that you will want to embed it into your django templates. Here are the sample embedding code:
def embed_handson_table(request):
"""
Renders two table in a handsontable
"""
content = excel.pe.save_book_as(
models=[Question, Choice],
dest_file_type="handsontable.html",
dest_embed=True,
)
content.seek(0)
return render(
request,
"custom-handson-table.html",
(continues on next page)
22 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
def embed_handson_table_from_a_single_table(request):
"""
Renders one table in a handsontable
"""
content = excel.pe.save_as(
model=Question, dest_file_type="handsontable.html", dest_embed=True
)
content.seek(0)
return render(
request,
"custom-handson-table.html",
{"handsontable_content": content.read()},
)
Previous example shows how to import a multi-sheet book. However, what exactly is needed to import only one sheet
instead? Before you proceed, please empty question and choice data using django admin.
Let’s visit this url first http://localhost:8000/polls/imports_sheet/, where you see a similar file upload form. This time
please choose sample-sheet.xls instead. Then look at django admin and see if the question data have been imported or
not.
def import_sheet(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
request.FILES["file"].save_to_database(
name_columns_by_row=2,
model=Question,
mapdict=["question_text", "pub_date", "slug"],
)
return HttpResponse("OK")
else:
Because it is a single sheet, the function to call is save_to_database() where you specify a model and its
mapping dictionary.
Have you noticed the extra parameter ‘name_columns_by_row’? Why is this needed? Well, normally you will not
need that if you have column names in the first row. In this example, the column names appears in the second row.
Please open sample-sheet.xls and have a look. The straight answer is because the column names in the data appears in
the 2nd row of the data matrix.
Note: If you have imported earlier excel sheet “sample-data.xls”, you will get the following warning in your console
output:
Warning: Bulk insertion got below exception. Trying to do it one by one slowly.
column slug is not unique <- reason
One row is ignored <- action
column slug is not unique
What is your favourite programming language?
One row is ignored
column slug is not unique
What is your favourite IDE?
This is because question data have been imported before. Django is raising IntegrityError. For more details please
read this part of code in pyexcel-io, and django-excel issue 2
In order to remove those warnings, what you can do is to empty all data using django admin and redo this single sheet
import again.
With new version pyexcel-io v0.1.0, you could provide the row initialization function that returns None in order to
skip a row in your import data. Inside the initialization function, you could also do database update. As long as it
returns None, django-excel will try to do bulk create the import data.
It is also quite common to download a portion of the data in a database table, for example the result of a search query.
With version 0.0.2, you can pass on a query sets to to make_response_from_query_sets() and generate an
excel sheet from it:
24 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
You can visit http://localhost:8000/polls/export/custom and will get the query set exported as a single sheet file as:
Let’s go to the admin page and update some votes for the choices.
In my case, I have updated all of them and have gotten something like this:
Now, let’s look at the survey result(http://localhost:8000/polls/survey_result/) for “What’s your favorite IDE?”:
26 Chapter 7. Tutorial
django-excel Documentation, Release 0.0.10
pyexcel-pygal provide you the common data visualization capability to show your data intuitively. Here is the code to
achieve that:
query_sets = Choice.objects.filter(question=question)
column_names = ["choice_text", "votes"]
def import_sheet_using_isave_to_database(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
28 Chapter 7. Tutorial
CHAPTER 8
The example application likes to have array but it is not just about arrays. Here is table of functions for all supported
data types:
data structure from file to data structures from data structures to response
dict get_dict() make_response_from_dict()
records get_records() make_response_from_records()
a list of lists get_array() make_response_from_array()
dict of a list of get_book_dict() make_response_from_book_dict()
lists
pyexcel. get_sheet() make_response()
Sheet
pyexcel. get_book() make_response()
Book
database table save_to_database() make_response_from_a_table()
isave_to_database()
a list of database save_book_to_database() make_response_from_tables()
tables isave_book_to_database()
a database query make_response_from_query_sets()
sets
a generator for iget_records()
records
a generator of iget_array()
lists
29
django-excel Documentation, Release 0.0.10
API Reference
django-excel attaches pyexcel functions to InMemoryUploadedFile and TemporaryUploadedFile. Hence, the fol-
lowing functions are available for the uploaded files, e.g. request.FILES[‘your_uploaded_file’].
django_excel.ExcelMixin.get_sheet(sheet_name=None, **keywords)
Parameters
• sheet_name – For an excel book, there could be multiple sheets. If it is left unspecified,
the sheet at index 0 is loaded. For ‘csv’, ‘tsv’ file, sheet_name should be None anyway.
• keywords – additional keywords to pyexcel.get_sheet()
Returns A sheet object
django_excel.ExcelMixin.get_array(sheet_name=None, **keywords)
Parameters
• sheet_name – same as get_sheet()
• keywords – additional keywords to pyexcel.get_array()
Returns a two dimensional array, a list of lists
django_excel.ExcelMixin.iget_array(sheet_name=None, **keywords)
Parameters
• sheet_name – same as get_sheet()
• keywords – additional keywords to pyexcel.iget_array()
Returns a generator for a two dimensional array, a list of lists
django_excel.ExcelMixin.get_dict(sheet_name=None, name_columns_by_row=0, **keywords)
Parameters
• sheet_name – same as get_sheet()
• name_columns_by_row – uses the first row of the sheet to be column headers by default.
31
django-excel Documentation, Release 0.0.10
33
django-excel Documentation, Release 0.0.10
Response methods
35
django-excel Documentation, Release 0.0.10
d
django_excel, 35
django_excel.ExcelMixin, 31
37
django-excel Documentation, Release 0.0.10
I
iget_array() (in module django_excel.ExcelMixin),
31
iget_records() (in module
django_excel.ExcelMixin), 32
isave_book_to_database() (in module
django_excel.ExcelMixin), 33
isave_to_database() (in module
django_excel.ExcelMixin), 32
M
make_response() (in module django_excel), 35
make_response_from_a_table() (in module
django_excel), 36
make_response_from_array() (in module
django_excel), 35
make_response_from_book_dict() (in module
django_excel), 36
39