1 LilSnippets-AddExcelDownload
Lance Edgar edited this page 2025-02-15 23:14:34 -06:00

Add Excel Download for a Master Web View

So you have a master web view, e.g. for your custom table. Now you might want to add a simple Excel download feature for it.

This example will build off the Widget example from LilSnippets/AddTable and LilSnippets/AddMasterView.

Enable Excel Download

The base class for master views provides most of the support for Excel download (XLSX file format); one need only enable it to use it with default behavior. This is done by setting an attribute on your master view class:

class WidgetsView(MasterView):

    results_downloadable_xlsx = True

With that in place, you can filter and sort the grid as you like, then click "Download results as XLSX" link to do just that. Note that this feature requires the corresponding permission to be granted for the user.

Customize Excel File

The default logic does what it can to inspect the columns of the underlying table for the master view. But it is often the case that the grid visible in the web UI will have additional columns from related tables, etc. Default logic does not address this, and in any case you may wish the Excel file to have a different set of columns from the web grid. To customize the download, you must override two methods:

class WidgetsView(MasterView):

    results_downloadable_xlsx = True

    def get_xlsx_fields(self):

        # fetch default fields; this will be a list
        fields = super(WidgetsView, self).get_xlsx_fields()

        # add a field
        fields.append('foo')

        return fields

    def get_xlsx_row(self, obj, fields):

        # make row dict per default logic
        row = super(WidgetsView, self).get_xlsx_row(obj, fields)

        # add value for our custom field
        row['foo'] = 'bar'

        return row