django4-tabular-export


Namedjango4-tabular-export JSON
Version 1.0.1 PyPI version JSON
download
home_pagehttps://github.com/francoborrelli/django4-tabular-export
SummarySimple spreadsheet exports for Django 4+
upload_time2024-04-24 22:35:55
maintainerNone
docs_urlNone
authorFranco Borrelli
requires_pythonNone
licenseCC0
keywords
VCS
bugtrack_url
requirements django xlsxwriter
Travis-CI
coveralls test coverage No coveralls.
              ------------------------
  django4-tabular-export
  ------------------------

> [!NOTE]  
> This version is compatible with Django 4+.

# 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_str](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.encoding.force_str)
    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](https://pypi.python.org/pypi/XlsxWriter) is one of the
    faster implementations and its memory-size optimizations are
    enabled.

# Quickstart

Install django4-tabular-export:

```py
pip install django4-tabular-export
```

Then use it in a project:
```py
from tabular_export.core import export_to_csv_response, export_to_excel_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(foo="…").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](https://docs.djangoproject.com/en/5.0/ref/contrib/admin/actions/)
which make it simple to add "Export to Excel" and "Export to CSV"
actions:

```py
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:

```py
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

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/francoborrelli/django4-tabular-export",
    "name": "django4-tabular-export",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "Franco Borrelli",
    "author_email": "francoborrelli96@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/17/85/06897b20e7170aeac5559188dca5050fdd4a7d090853046063e4aec1e840/django4_tabular_export-1.0.1.tar.gz",
    "platform": null,
    "description": "  ------------------------\n  django4-tabular-export\n  ------------------------\n\n> [!NOTE]  \n> This version is compatible with Django 4+.\n\n# Documentation\n\nThis module contains functions which take (headers, rows) pairs and\nreturn HttpResponses with either XLSX or CSV downloads and Django admin\nactions which can be added to any ModelAdmin for generic exports. It\nprovides two functions (`export_to_csv_response` and\n`export_to_xlsx_response`) which take a filename, a list of column\nheaders, and a Django `QuerySet`, list-like object, or generator and\nreturn a response.\n\n## Goals\n\n-   This project is not intended to be a general-purpose spreadsheet\n    manipulation library. The only goal is to export data quickly and\n    safely.\n-   The API is intentionally simple, giving you full control over the\n    display and formatting of headers or your data. `flatten_queryset`\n    has special handling for only two types of data: `None` will be\n    converted to an empty string and `date` or `datetime` instances will\n    serialized using `isoformat()`. All other values will be specified\n    as the text data type to avoid data corruption in Excel if the\n    values happen to resemble a date in the current locale.\n-   **Unicode-safety**: input values, including lazy objects, are\n    converted using Django\\'s\n    [force_str](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.encoding.force_str)\n    function and will always be emitted as UTF-8\n-   **Performance**: the code is known to work with data sets up to\n    hundreds of thousands of rows. CSV responses use\n    `StreamingHttpResponse`, use minimal memory, and start very quickly.\n    Excel (XLSX) responses cannot be streamed but\n    [xlsxwriter](https://pypi.python.org/pypi/XlsxWriter) is one of the\n    faster implementations and its memory-size optimizations are\n    enabled.\n\n# Quickstart\n\nInstall django4-tabular-export:\n\n```py\npip install django4-tabular-export\n```\n\nThen use it in a project:\n```py\nfrom tabular_export.core import export_to_csv_response, export_to_excel_response, flatten_queryset\n\ndef my_view(request):\n    return export_to_csv_response('test.csv', ['Column 1'], [['Data 1'], ['Data 2']])\n\n\ndef my_other_view(request):\n    headers = ['Title', 'Date Created']\n    rows = MyModel.objects.values_list('title', 'date_created')\n    return export_to_excel_response('items.xlsx', headers, rows)\n\n\ndef export_using_a_generator(request):\n    headers = ['A Number']\n\ndef my_generator():\n    for i in range(0, 100000):\n        yield (i, )\n\n  return export_to_excel_response('numbers.xlsx', headers, my_generator())\n\ndef export_renaming_columns(request):\n    qs = MyModel.objects.filter(foo=\"\u2026\").select_related(\"\u2026\")\n    headers, data = flatten_queryset(qs, field_names=['title', 'related_model__title_en'], extra_verbose_names={'related_model__title_en': 'English Title'})\n    return export_to_csv_response('custom_export.csv', headers, data)\n```\n\n## Admin Integration\n\nThere are two convenience [admin\nactions](https://docs.djangoproject.com/en/5.0/ref/contrib/admin/actions/)\nwhich make it simple to add \"Export to Excel\" and \"Export to CSV\"\nactions:\n\n```py\nfrom tabular_export.admin import export_to_csv_action, export_to_excel_action\n\nclass MyModelAdmin(admin.ModelAdmin):\n    actions = (export_to_excel_action, export_to_csv_action)\n```\n\nThe default columns will be the same as you would get calling\n`values_list` on your `ModelAdmin`\\'s default queryset as returned by\n`ModelAdmin.get_queryset()`. If you want to customize this, simply\ndeclare a new action on your `ModelAdmin` which does whatever data\npreparation is necessary:\n\n```py\nfrom tabular_export.admin import export_to_excel_action\n\nclass MyModelAdmin(admin.ModelAdmin):\n    actions = ('export_batch_summary_action', )\n\ndef export_batch_summary_action(self, request, queryset):\n    headers = ['Batch Name', 'My Computed Field']\n    rows = queryset.annotate(\"\u2026\").values_list('title', 'computed_field_name')\n    return export_to_excel_response('batch-summary.xlsx', headers, rows)\n    export_batch_summary_action.short_description = 'Export Batch Summary'\n```\n\n## Debugging\n\nThe `TABULAR_RESPONSE_DEBUG = True` setting will cause all views to\nreturn HTML tables\n",
    "bugtrack_url": null,
    "license": "CC0",
    "summary": "Simple spreadsheet exports for Django 4+",
    "version": "1.0.1",
    "project_urls": {
        "Homepage": "https://github.com/francoborrelli/django4-tabular-export"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "920689193b2901a3f2f8c095aca51a3c6ec9d1eae8fbc257c5be35b6a8cc17dc",
                "md5": "cfbb8d77e57943b12b5bcb8c1d89a871",
                "sha256": "b4d9df5d7101806bfc983f5a13a6b35a51fa56754d1f9f1469bad8ae45ce2fd8"
            },
            "downloads": -1,
            "filename": "django4_tabular_export-1.0.1-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "cfbb8d77e57943b12b5bcb8c1d89a871",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 11386,
            "upload_time": "2024-04-24T22:35:54",
            "upload_time_iso_8601": "2024-04-24T22:35:54.441859Z",
            "url": "https://files.pythonhosted.org/packages/92/06/89193b2901a3f2f8c095aca51a3c6ec9d1eae8fbc257c5be35b6a8cc17dc/django4_tabular_export-1.0.1-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "178506897b20e7170aeac5559188dca5050fdd4a7d090853046063e4aec1e840",
                "md5": "a094917d5cfc50a3c8e450cd062405df",
                "sha256": "5a84dd99dffffad9551fb692915b71f6f39fadf216d4a8331b5166cdffb026c8"
            },
            "downloads": -1,
            "filename": "django4_tabular_export-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "a094917d5cfc50a3c8e450cd062405df",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 14182,
            "upload_time": "2024-04-24T22:35:55",
            "upload_time_iso_8601": "2024-04-24T22:35:55.884517Z",
            "url": "https://files.pythonhosted.org/packages/17/85/06897b20e7170aeac5559188dca5050fdd4a7d090853046063e4aec1e840/django4_tabular_export-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-24 22:35:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "francoborrelli",
    "github_project": "django4-tabular-export",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "django",
            "specs": [
                [
                    "==",
                    "4.2.11"
                ]
            ]
        },
        {
            "name": "xlsxwriter",
            "specs": []
        }
    ],
    "tox": true,
    "lcname": "django4-tabular-export"
}
        
Elapsed time: 0.27023s