Welcome to Flask-Excel’s documentation!

Flask-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 Pythonic a list of lists, a list of records(dictionaries), dictionaries of lists. And vice versa. Hence it lets you focus on data in Flask based web development, instead of file formats.

The highlighted features are:

  1. excel data import into and export from databases
  2. turn uploaded excel file directly into Python data struture
  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:
A list of file formats supported by external plugins
Plugins Supported file formats
xls xls, xlsx(r), xlsm(r)
xlsx xlsx
ods ods (python 2.6, 2.7)
ods3 ods (python 2.7, 3.3, 3.4)

This library make infomation 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 persistence. It uses pyexcel and its plugins: 1) to provide one uniform programming interface to handle csv, tsv, xls, xlsx, xlsm and ods formats. 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.

Quick start

A minimal application may look like this:

from flask import Flask, request, jsonify
from flask.ext import excel

app=Flask(__name__)

@app.route("/upload", methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        return jsonify({"result": request.get_array('file')})
    return '''
    <!doctype html>
    <title>Upload an excel file</title>
    <h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
    <form action="" method=post enctype=multipart/form-data><p>
    <input type=file name=file><input type=submit value=Upload>
    </form>
    '''

@app.route("/download", methods=['GET'])
def download_file():
    return excel.make_response_from_array([[1,2], [3, 4]], "csv")

# insert database related code here

if __name__ == "__main__":
    app.run()

The tiny application exposes two urls: one for file upload and the other for file donload. The former url presents a simple file upload html and responds back in json with the content of the uploaded file. The file upload handler uses request.get_array to parse the uploaded file and gets an array back. The parameter file is coded in the html form:

<input ... name=file>

The latter simply throws back a csv file whenever a http request is made to http://localhost:50000/download/. excel.make_response_from_array takes a list of lists and a file type as parameters and sets up the mime type of the http response. If you would like to give ‘tsvz’ a go, please change “csv” to “tsvz”.

More excel file formats

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 include one or all of the following import lines right after Flask-Excel is imported:

import pyexcel.ext.xls
import pyexcel.ext.xlsx
import pyexcel.ext.ods

Data import and export

Continue with the previous example, the data import and export will be explained. You can copy the following code in their own appearing sequence and paste them after the place holder:

# insert database related code here

Alernatively, you can find the complete example on github

Now let’s add the following imports first:

from flask.ext.sqlalchemy import SQLAlchemy # sql operations
import pyexcel.ext.xls # import it to be able to handle xls file format

Now configure the database connection. Sqllite will be used and tmp.db will be used and can be found in your current working directory:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tmp.db'
db = SQLAlchemy(app)

And paste some models from Flask-SQLAlchemy’s documentation:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
        backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title

class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Category %r>' % self.name

Now let us create the tables in the database:

db.create_all()

Write up the view functions for data import:

@app.route("/import", methods=['GET', 'POST'])
def doimport():
    if request.method == 'POST':
        def category_init_func(row):
            c = Category(row['name'])
            c.id = row['id']
            return c
        def post_init_func(row):
            c = Category.query.filter_by(name=row['category']).first()
            p = Post(row['title'], row['body'], c, row['pub_date'])
            return p
        request.save_book_to_database(field_name='file', session=db.session,
                                      tables=[(Category, category_init_func),
                                              (Post, post_init_func)])
        return "Saved"
    return '''
    <!doctype html>
    <title>Upload an excel file</title>
    <h1>Excel file upload (xls, xlsx, ods please)</h1>
    <form action="" method=post enctype=multipart/form-data><p>
    <input type=file name=file><input type=submit value=Upload>
    </form>
    '''

Write up the view function for data export:

@app.route("/export", methods=['GET'])
def doexport():
    return excel.make_response_from_tables(db.session, [Category, Post], "xls")

All supported data types

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 lists get_book_dict() make_response_from_book_dict()
Sheet get_sheet() make_response()
Book get_book() make_response()
database table save_to_database() make_response_from_a_table()
a list of database tables save_book_to_database() make_response_from_tables()

See more examples of the data structures in pyexcel documentation

API Reference

class flask_excel.ExcelRequest(environ, populate_request=True, shallow=False)[source]
get_sheet(field_name=None, sheet_name=None, **keywords)
Parameters:
  • field_name – the file field name in the html form for file upload
  • 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 library
Returns:

A sheet object

The following html form, the field_name should be “file”:

<!doctype html>
<title>Upload an excel file</title>
<h1>Excel file upload (csv, tsv, csvz, tsvz only)</h1>
<form action="" method=post enctype=multipart/form-data><p>
<input type=file name=file><input type=submit value=Upload>
</form>
get_array(field_name=None, sheet_name=None, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • sheet_name – same as get_sheet()
  • keywords – additional keywords to pyexcel library
Returns:

a two dimensional array, a list of lists

get_dict(field_name=None, sheet_name=None, name_columns_by_row=0, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • sheet_name – same as get_sheet()
  • name_columns_by_row – uses the first row of the sheet to be column headers by default.
  • keywords – additional keywords to pyexcel library
Returns:

a dictionary of the file content

get_records(field_name=None, sheet_name=None, name_columns_by_row=0, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • sheet_name – same as get_sheet()
  • name_columns_by_row – uses the first row of the sheet to be record field names by default.
  • keywords – additional keywords to pyexcel library
Returns:

a list of dictionary of the file content

get_book(field_name=None, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • keywords – additional keywords to pyexcel library
Returns:

a two dimensional array, a list of lists

get_book_dict(field_name=None, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • keywords – additional keywords to pyexcel library
Returns:

a two dimensional array, a list of lists

save_to_database(field_name=None, table=None, **keywords)
Parameters:
  • field_name – same as get_sheet()
  • table – a database table or a tuple which have this sequence (table, table_init_func, mapdict, name_columns_by_row, name_rows_by_column)
  • table_init_func – it is needed when your table had custom __init__ function
  • mapdict – it is needed when the uploaded sheet had a different column headers than the table column names this mapdict tells which column of the upload sheet maps to which column of the table
  • name_columns_by_row – uses the first row of the sheet to be column headers by default. if you use name_rows_by_column, please set this to -1
  • name_rows_by_column – uses a column to name rows.
  • keywords – additional keywords to pyexcel library
save_book_to_database(field_name=None, tables=None, **keywords)
Parameters:
  • field_name – save as get_sheet()
  • tables – a list of database tables or tuples which have this sequence (table, table_init_func, mapdict, name_columns_by_row, name_rows_by_column)
  • table_init_funcs – it is needed when your table had custom __init__ function
  • mapdict – it is needed when the uploaded sheet had a different column headers than the table column names. this mapdict tells which column of the upload sheet maps to which column of the table
  • name_columns_by_row – uses the first row of each sheet to be column headers by default. if you use name_rows_by_column, please set this to -1
  • name_rows_by_column – uses a column to name rows.
  • keywords – additional keywords to pyexcel library

Response methods

flask_excel.make_response(pyexcel_instance, file_type, status=200)
Parameters:
  • pyexcel_instance – pyexcel.Sheet or pyexcel.Book
  • file_type

    one of the following strings:

    • ‘csv’
    • ‘tsv’
    • ‘csvz’
    • ‘tsvz’
    • ‘xls’
    • ‘xlsx’
    • ‘xlsm’
    • ‘ods’
  • status – unless a different status is to be returned.
flask_excel.make_response_from_array(array, file_type, status=200)
Parameters:
flask_excel.make_response_from_dict(dict, file_type, status=200)
Parameters:
flask_excel.make_response_from_records(records, file_type, status=200)
Parameters:
flask_excel.make_response_from_book_dict(book_dict, file_type, status=200)
Parameters:

Indices and tables

Fork me on GitHub