Package: drf-renderer-xlsx-ko
Django REST Framework Renderer: XLSXdrf-renderer-xlsxprovides an XLSX renderer for Django REST Framework. It uses OpenPyXL to create the spreadsheet and returns the data.RequirementsIt may work with earlier versions, but has been tested with the following:Python >= 3.6Django >= 2.2Django REST Framework >= 3.6OpenPyXL >= 2.4Installationpipinstalldrf-renderer-xlsxThen add the following to yourREST_FRAMEWORKsettings:REST_FRAMEWORK={...'DEFAULT_RENDERER_CLASSES':('rest_framework.renderers.JSONRenderer','rest_framework.renderers.BrowsableAPIRenderer','drf_renderer_xlsx.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_renderer_xlsx.mixinsimportXLSXFileMixinfromdrf_renderer_xlsx.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.Configuring StylesStyles can be added to your worksheet header, column header row, and body rows, from view attributesheader,column_header,body. Any arguments fromthe OpenPyXL packagecan be used for font, alignment, fill and border_side (border will always be all side of cell).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,}Also you can dynamically generate style attributes in methodsget_body,get_header,get_column_header.defget_header(self):starttime,endtime=parse_times(request=self.request)datetime_format="%H:%M:%S%d.%m.%Y"return{'tab_title':'MyReport','header_title':'Report from{}to{}'.format(starttime.strftime(datetime_format),endtime.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 addcolorfield to your serializer and fill body rows.classExampleSerializer(serializers.Serializer):color=serializers.SerializerMethodField()defget_color(self,instance):color_map={'w':'FFFFFFCC','a':'FFFFCCCC'}returncolor_map.get(instance.alarm_level,'FFFFFFFF')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).Name boolean valuesTrueandFalseas values for boolean fields are not always the best representation and don't support translation. This can be controlled withxlsx_boolean_labels.xlsx_boolean_labels = {True: _('Yes'), False: _('No')}will replaceTruewithYesandFalsewithNo.Format datesTo format dates differently than what DRF returns (eg. 2013-01-29T12:34:56.000000Z)xlsx_date_format_mappingstakes a ´dict` with the field name as its key and the date(time) format as its value:xlsx_date_format_mappings = {
    'created_at': '%d.%m.%Y %H:%M',
    'updated_at': '%d.%m.%Y %H:%M'
}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 probably 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:def reverse_text(val):
    return val[::-1]

xlsx_custom_mappings = {
    'description': reverse_text
}Release NotesRelease notes areavailable on GitHub.MaintainerTimothy AllenatThe Wharton SchoolThis package is maintained 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 package users.Contributors (Thank You!)Armaan TobaccowallaDavis HauptEric WangFelipe SchmittffruitGonzalo AyusoNick KozheninPavel BryantsevPavel TolstolytkoThomas WillemsTim