'How to add header / footer on export on django import-export?

I'm using the django-import-export plugin in admin, and i would like to add a header/footer(images) when exporting data.

Is there a way to get a handle on the excel or pdf object maybe when overriding export or before_export ?



Solution 1:[1]

The django-import-export modules' core functionalities depend on the other package named tablib. You can't achieve what you are intended to do merely by overriding few methods which belong to django-import-export package since the export().format_name property belongs to tablib package.


Workaround (the hard one)

  1. Create a new format or edit the existing. ref Adding New Formats (tablib doc)
  2. After editing the source code, build your own tablib python package
  3. build your own django-import-export by wiring-up the custom tablib package
  4. wire-up the custom django-import-export package in your django project

Solution 2:[2]

You can do this by overriding get_export_data() in a custom Admin class. The super class get_export_data() will return the xlsx data. This can be loaded into a Openpyxl workbook and then modified. This only works with 'xlsx' files.

(example taken from django-import-export example app)

from io import BytesIO

from django.core.files.temp import NamedTemporaryFile
from openpyxl import load_workbook

class BookAdmin(ImportExportMixin, admin.ModelAdmin):
    list_display = ('name', 'author', 'added')
    list_filter = ['categories', 'author']
    resource_class = BookResource

    def get_export_data(self, file_format, queryset, *args, **kwargs):
        """
        Returns file_format representation for given queryset.
        """
        export_data = super().get_export_data(file_format, queryset, *args, **kwargs)
        wb = load_workbook(BytesIO(export_data))
        ws = wb.active
        ws.insert_rows(1)
        ws["A1"] = "NEW ROW"

        with NamedTemporaryFile() as f:
            wb.save(f.name)
            data = BytesIO(f.read())

        return data

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JPG
Solution 2 Matthew Hegarty