Skip to content

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

1 watching

Forks

Repository files navigation

XLSXDocument

This is a wrapper for openpyxl which makes creating XLSX documents with the purpose of exporting data less boring:

from xlsxdocument import XLSXDocument

def xlsx_export(request):
    some_data = Bla.objects.all()

    xlsx = XLSXDocument()
    xlsx.table_from_queryset(Bla.objects.all())
    return xlsx.to_response("bla.xlsx")

Adding in additional cells at the end is also possible:

xlsx = XLSXDocument()
xlsx.table_from_queryset(
    Bla.objects.all(),
    additional=[(
        "Full URL",
        lambda instance: "https://example.com%s" % (
            instance.get_absolute_url(),
        ),
    )],
)

For lower-level control, use add_sheet() and table() directly to build sheets from arbitrary data:

xlsx = XLSXDocument()
xlsx.add_sheet("Sales")
xlsx.table(
    titles=["Product", "Quantity", "Price"],
    rows=[
        ["Widget A", 10, 9.99],
        ["Widget B", 5, 24.99],
    ],
)
return xlsx.to_response("sales.xlsx")

Strings starting with = are written as text, not as formulas, since exported data is often untrusted (formula injection). Wrap intentional formulas in Formula:

from xlsxdocument import Formula, XLSXDocument

xlsx.table(
    titles=["Product", "Quantity"],
    rows=[
        ["Widget A", 10],
        ["Widget B", 5],
        ["Total", Formula("=SUM(B2:B3)")],
    ],
)

You can also add multiple sheets to a single document:

xlsx = XLSXDocument()

xlsx.add_sheet("Orders")
xlsx.table(["ID", "Customer", "Total"], orders_data)

xlsx.add_sheet("Products")
xlsx.table(["SKU", "Name", "Stock"], products_data)

return xlsx.to_response("export.xlsx")

You can also easily add the facility to export rows to Django's administration interface:

from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from xlsxdocument import export_selected

from app import models


class AttendanceAdmin(admin.ModelAdmin):
    list_filter = ["event"]
    actions = [export_selected]


admin.site.register(models.Event)
admin.site.register(models.Attendance, AttendanceAdmin)

If you require additional columns with export_selected use this snippet instead:

from xlsxdocument import create_export_selected

class AttendanceAdmin(...):
    actions = [
        create_export_selected(
            additional=[
                # ... see above
            ]
        )
    ]

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages