Skip to main content

Simple spreadsheet exports from Django

Project description

Landscape.io Code Quality https://travis-ci.org/LibraryOfCongress/django-tabular-export.png?branch=master

Simple spreadsheet exports from Django

Documentation

This module contains functions which take (headers, rows) pairs and return HttpResponses with either XLSX or CSV downloads and Django admin actions which can be added to any ModelAdmin for generic exports. It provides two functions (export_to_csv_response and export_to_xlsx_response) which take a filename, a list of column headers, and a Django QuerySet, list-like object, or generator and return a response.

Goals

  • This project is not intended to be a general-purpose spreadsheet manipulation library. The only goal is to export data quickly and safely.

  • The API is intentionally simple, giving you full control over the display and formatting of headers or your data. flatten_queryset has special handling for only two types of data: None will be converted to an empty string and date or datetime instances will serialized using isoformat(). All other values will be specified as the text data type to avoid data corruption in Excel if the values happen to resemble a date in the current locale.

  • Unicode-safety: input values, including lazy objects, are converted using Django’s force_text function and will always be emitted as UTF-8

  • Performance: the code is known to work with data sets up to hundreds of thousands of rows. CSV responses use StreamingHttpResponse, use minimal memory, and start very quickly. Excel (XLSX) responses cannot be streamed but xlsxwriter is one of the faster implementations and its memory-size optimizations are enabled.

Quickstart

Install django-tabular-export:

pip install django-tabular-export

Then use it in a project:

from tabular_export import export_to_csv_response, export_to_xlsx_response, flatten_queryset

def my_view(request):
    return export_to_csv_response('test.csv', ['Column 1'], [['Data 1'], ['Data 2'], …])


def my_other_view(request):
    headers = ['Title', 'Date Created']
    rows = MyModel.objects.values_list('title', 'date_created')
    return export_to_excel_response('items.xlsx', headers, rows)


def export_using_a_generator(request):
    headers = ['A Number']

    def my_generator():
        for i in range(0, 100000):
            yield (i, )

    return export_to_excel_response('numbers.xlsx', headers, my_generator())

def export_renaming_columns(request)
    qs = MyModel.objects.filter(…).select_related(…)
    headers, data = flatten_queryset(qs, field_names=['title', 'related_model__title_en'],
                                     extra_verbose_names={'related_model__title_en': 'English Title'})
    return export_to_csv_response('custom_export.csv', headers, data)

Admin Integration

There are two convenience admin actions which make it simple to add “Export to Excel” and “Export to CSV” actions:

from tabular_export.admin import export_to_csv_action, export_to_excel_action

class MyModelAdmin(admin.ModelAdmin):
    actions = (export_to_excel_action, export_to_csv_action)
    …

The default columns will be the same as you would get calling values_list on your ModelAdmin’s default queryset as returned by ModelAdmin.get_queryset(). If you want to customize this, simply declare a new action on your ModelAdmin which does whatever data preparation is necessary:

from tabular_export.admin import export_to_excel_action

class MyModelAdmin(admin.ModelAdmin):
    actions = ('export_batch_summary_action', )

    def export_batch_summary_action(self, request, queryset):
        headers = ['Batch Name', 'My Computed Field']
        rows = queryset.annotate(…).values_list('title', 'computed_field_name')
        return export_to_excel_response('batch-summary.xlsx', headers, rows)
    export_batch_summary_action.short_description = 'Export Batch Summary'

Debugging

The TABULAR_RESPONSE_DEBUG = True setting will cause all views to return HTML tables

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-tabular-export-1.0.0.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

django_tabular_export-1.0.0-py2.py3-none-any.whl (10.8 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file django-tabular-export-1.0.0.tar.gz.

File metadata

File hashes

Hashes for django-tabular-export-1.0.0.tar.gz
Algorithm Hash digest
SHA256 6bec1cd1359cccd04adaa0a8e634c8d8eea379bed7697179cad9362729aa9824
MD5 ac6b810b07994ec6b6d111a376a470ee
BLAKE2b-256 2933aca4bfa68f042e8ba0c1925db108dc0ee51b397104a7551cce6ea1d812f8

See more details on using hashes here.

File details

Details for the file django_tabular_export-1.0.0-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for django_tabular_export-1.0.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 6d3f4a7bc095bdae42b93c802b62b5b27749f153cd4f6a873d856d657b33c11f
MD5 93c8ec68229a8950a9bbfff2c7c9b09f
BLAKE2b-256 b0d2d8297d61094b5d262204d307132e4a215e2fddcd401a2066d2ac03f75bfc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page