Package: drf-excel
DRF Excel: Django REST Framework Excel Spreadsheet (xlsx) Rendererdrf-excelprovides an Excel spreadsheet (xlsx) renderer for Django REST Framework. It uses OpenPyXL to create the spreadsheet and provide the file to the end user.RequirementsWe aim to support Django'scurrently supported versions, as well as:Django REST Framework >= 3.14OpenPyXL >= 2.4Installationpipinstalldrf-excelThen add the following to yourREST_FRAMEWORKsettings:REST_FRAMEWORK={...'DEFAULT_RENDERER_CLASSES':('rest_framework.renderers.JSONRenderer','rest_framework.renderers.BrowsableAPIRenderer','drf_excel.renderers.XLSXRenderer',),}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 theContent-Dispositionheader. If nofilenameis provided, it will default toexport.xlsx. For example:fromrest_framework.viewsetsimportReadOnlyModelViewSetfromdrf_excel.mixinsimportXLSXFileMixinfromdrf_excel.renderersimportXLSXRendererfrom.modelsimportMyExampleModelfrom.serializersimportMyExampleSerializerclassMyExampleViewSet(XLSXFileMixin,ReadOnlyModelViewSet):queryset=MyExampleModel.objects.all()serializer_class=MyExampleSerializerrenderer_classes=(XLSXRenderer,)filename='my_export.xlsx'TheXLSXFileMixinalso provides aget_filename()method which can be overridden, if you prefer to provide a filename programmatically instead of thefilenameattribute.Upgrading to 2.0.0To upgrade todrf_excel2.0.0 fromdrf_renderer_xlsx, update your import paths:from drf_renderer_xlsx.mixins import XLSXFileMixinbecomesfrom drf_excel.mixins import XLSXFileMixin.drf_renderer_xlsx.renderers.XLSXRendererbecomesdrf_excel.renderers.XLSXRenderer.xlsx_date_format_mappingshas been removed in favor ofcolumn_data_styleswhich provides more flexibilityConfiguring StylesStyles can be added to your worksheet header, column header row, body and column data from view attributesheader,column_header,body,column_data_styles. Any arguments fromthe OpenPyXL packagecan 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 styleNote that column data styles can take an extra 'format' argument that followsopenpyxl formats.classMyExampleViewSet(XLSXFileMixin,ReadOnlyModelViewSet):queryset=MyExampleModel.objects.all()serializer_class=MyExampleSerializerrenderer_classes=(XLSXRenderer,)column_header={'titles':["Column_1_name","Column_2_name","Column_3_name",],'column_width':[17,30,17],'height':25,'style':{'fill':{'fill_type':'solid','start_color':'FFCCFFCC',},'alignment':{'horizontal':'center','vertical':'center','wrapText':True,'shrink_to_fit':True,},'border_side':{'border_style':'thin','color':'FF000000',},'font':{'name':'Arial','size':14,'bold':True,'color':'FF000000',},},}body={'style':{'fill':{'fill_type':'solid','start_color':'FFCCFFCC',},'alignment':{'horizontal':'center','vertical':'center','wrapText':True,'shrink_to_fit':True,},'border_side':{'border_style':'thin','color':'FF000000',},'font':{'name':'Arial','size':14,'bold':False,'color':'FF000000',}},'height':40,}column_data_styles={'distance':{'alignment':{'horizontal':'right','vertical':'top',},'format':'0.00E+00'},'created_at':{'format':'d.m.y h:mm',}}You can dynamically generate style attributes in methodsget_body,get_header,get_column_header,get_column_data_styles.defget_header(self):start_time,end_time=parse_times(request=self.request)datetime_format="%H:%M:%S%d.%m.%Y"return{'tab_title':'MyReport',# title of tab/workbook'use_header':True,# show the header_title'header_title':'Report from{}to{}'.format(start_time.strftime(datetime_format),end_time.strftime(datetime_format),),'height':45,'img':'app/images/MyLogo.png','style':{'fill':{'fill_type':'solid','start_color':'FFFFFFFF',},'alignment':{'horizontal':'center','vertical':'center','wrapText':True,'shrink_to_fit':True,},'border_side':{'border_style':'thin','color':'FF000000',},'font':{'name':'Arial','size':16,'bold':True,'color':'FF000000',}}}Also, you can add therow_colorfield to your serializer and fill body rows.classExampleSerializer(serializers.Serializer):row_color=serializers.SerializerMethodField()defget_row_color(self,instance):color_map={'w':'FFFFFFCC','a':'FFFFCCCC'}returncolor_map.get(instance.alarm_level,'FFFFFFFF')Configuring Sheet View OptionsView options followopenpyxl sheet view optionsThey can be set in the view as a propertysheet_view_options:classMyExampleViewSet(serializers.Serializer):sheet_view_options={'rightToLeft':True,'showGridLines':False}or using methodget_sheet_view_options:classMyExampleViewSet(serializers.Serializer):defget_sheet_view_options(self):return{'rightToLeft':True,'showGridLines':False}Controlling XLSX headers and valuesUse Serializer Field labels as header namesBy default, headers will use the same 'names' as they are returned by the API. This can be changed by settingxlsx_use_labels = Trueinside 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 astitle = serializers.CharField(label=_("Some title"))would returnSome titleinstead oftitle, also supporting translations. If no label is set, it will fall back to usingtitle.Ignore fieldsBy default, all fields are exported, but you might want to exclude some fields from your export. To do so, you can set an array with fields you want to exclude:xlsx_ignore_headers = [<excluded fields>].This also works with nested fields, separated with a dot (i.e.icon.url).Date/time and number formattingFormatting for cells followsopenpyxl formats.To set global formats, set the following variables insettings.py:# Date formatsDRF_EXCEL_DATETIME_FORMAT='mm-dd-yy h:mm AM/PM'DRF_EXCEL_DATE_FORMAT='mm-dd-yy'DRF_EXCEL_TIME_FORMAT='h:mm AM/PM'# Number formatsDRF_EXCEL_INTEGER_FORMAT='0%'DRF_EXCEL_DECIMAL_FORMAT='0.00E+00'Name boolean valuesTrueandFalseas values for boolean fields are not always the best representation and don't support translation.This can be controlled with in you API view withxlsx_boolean_labels.xlsx_boolean_labels = {True: _('Yes'), False: _('No')}will replaceTruewithYesandFalsewithNo.This can also be set globally in settings.py:DRF_EXCEL_BOOLEAN_DISPLAY = {True: _('Yes'), False: _('No')}Custom columnsYou 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 passingxlsx_custom_cols.xlsx_custom_cols={'my_custom_col.val1.title':{'label':'Custom column!','formatter':custom_value_formatter}}### Example function:defcustom_value_formatter(val):returnval+'!!!'### Example response:{results:[{title:'XLSX renderer',url:'https://github.com/wharton/drf-excel'returned_dict:{val1:{title:'Sometimes'},val2:{title:'There is no way around'}}}]}When nolabelis passed,drf-excelwill display the key name in the header.formatteris 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 mappingsAssuming you have a field that returns adictinstead of a simplestr, you might not want to return the whole object but only a value of it. Let's saystatusreturns{ value: 1, display: 'Active' }. To return thedisplayvalue in thestatuscolumn, 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_mappingsalso takes functions as values. Assuming we have a fielddescription, and for some strange reason want to reverse the text, we can do this:defreverse_text(val):returnval[::-1]xlsx_custom_mappings={'description':reverse_text}Release Notes and ContributorsRelease notesOur wonderful contributorsMaintainersTimothy AllenatThe Wharton SchoolThomas WillemsMathieu RampantThis package was created by the staff ofWharton Research Data Services. We are thrilled thatThe Wharton Schoolallows 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.