drf-excel provides an Excel spreadsheet (xlsx) renderer for Django REST Framework. It uses OpenPyXL to create the spreadsheet and provide the file to the end user.
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the Content-Disposition header. If no is provided, it will default to . For example:
filename
export.xlsx
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from .models import MyExampleModel
from .serializers import MyExampleSerializer
class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
queryset = MyExampleModel.objects.all()
serializer_class = MyExampleSerializer
renderer_classes = (XLSXRenderer,)
filename = 'my_export.xlsx'
pagination_class = None # Only required if custom pagination is used
The XLSXFileMixin also provides a get_filename() method which can be overridden, if you prefer to provide a filename programmatically instead of the filename attribute.
Upgrading to 2.0.0
To upgrade to drf_excel 2.0.0 from drf_renderer_xlsx, update your import paths:
from drf_renderer_xlsx.mixins import XLSXFileMixin becomes from drf_excel.mixins import XLSXFileMixin.
xlsx_date_format_mappings has been removed in favor of column_data_styles which provides more flexibility
Configuring Styles
Styles can be added to your worksheet header, column header row, body and column data from view attributes header, column_header, body, column_data_styles. Any arguments from the OpenPyXL package can be used for font, alignment, fill and border_side (border will always be all side of cell).
If provided, column data styles will override body style
Note that column data styles can take an extra 'format' argument that follows openpyxl formats.
By default, headers will use the same 'names' as they are returned by the API. This can be changed by setting xlsx_use_labels = True inside your API View.
Instead of using the field names, the export will use the labels as they are defined inside your Serializer. A serializer field defined as title = serializers.CharField(label=_("Some title")) would return Some title instead of title, also supporting translations. If no label is set, it will fall back to using title.
Auto filter header fields
Filters can automatically be added to the header row by setting xlsx_auto_filter = True. The filter will include all header columns in the worksheet.
Specify or ignore fields
By default, all fields are exported. However, this behavior can be changed.
To include only a specified list of fields, provide them with: xlsx_specify_headers = [<fields to include>]. Conversely, to exclude certain fields from your export, provide them with: xlsx_ignore_headers = [<excluded fields>].
These both work with nested fields, separated with a dot (i.e. icon.url). Naming a nested serializer itself (i.e. icon) includes all of the fields below it.
A few things worth knowing:
When both options are set, xlsx_ignore_headers wins: a field named in both is excluded.
Columns follow the order in which the fields are declared on the serializer, not the order of xlsx_specify_headers. Keep this in mind when combining it with the titles of column_header, which are applied positionally.
Names that match no serializer field are ignored silently, so a typo results in a missing column rather than an error.
You might find yourself explicitly returning a dict in your API response and would like to use its data to display additional columns. This can be done by passing xlsx_custom_cols.
xlsx_custom_cols = {
'my_custom_col.val1.title': {
'label': 'Custom column!',
'formatter': custom_value_formatter
}
}
### Example function:
def custom_value_formatter(val):
return val + '!!!'
### Example response:
{
results: [
{
title: 'XLSX renderer',
url: 'https://github.com/django-commons/drf-excel'
returned_dict: {
val1: {
title: 'Sometimes'
},
val2: {
title: 'There is no way around'
}
}
}
]
}
When no label is passed, drf-excel will display the key name in the header.
formatter is also optional and accepts a function, which will then receive the value it is mapped to (it would receive "Sometimes" and return "Sometimes!!!" in our example).
Custom mappings
Assuming you have a field that returns a dict instead of a simple str, you might not want to return the whole object but only a value of it. Let's say status returns { value: 1, display: 'Active' }. To return the display value in the status column, we can do this:
xlsx_custom_mappings = {
'status': 'display'
}
A more common case is that you want to change how a value is formatted. xlsx_custom_mappings also takes functions as values. Assuming we have a field description, and for some strange reason want to reverse the text, we can do this:
This package is a member of Django Commons and adheres to the community's Code of Conduct. This package was created by the staff of Wharton Research Data Services. We are thrilled that The Wharton School allows us a certain amount of time to contribute to open-source projects. We add features as they are necessary for our projects, and try to keep up with Issues and Pull Requests as best we can. Due to constraints of time (our full time jobs!), Feature Requests without a Pull Request may not be implemented, but we are always open to new ideas and grateful for contributions and our users.
Works well with
Use together with drf-excel: extensions, drivers, servers and companion tools.
DjangoPythie’s Index: 91A high-level Python web framework that encourages rapid development and clean, pragmatic design.52.8M downloads/mo