Skip to main content

Django REST Framework renderer for spreadsheet (xlsx) files.

Project description

Django REST Framework Renderer: XLSX

drf-renderer-xlsx provides an XLSX renderer for Django REST Framework. It uses OpenPyXL to create the spreadsheet and returns the data.

Requirements

It may work with earlier versions, but has been tested with the following:

  • Python >= 3.5 (Python 2 will not work with Unicode)
  • Django >= 1.11
  • Django REST Framework >= 3.6
  • OpenPyXL >= 2.4

Installation

pip install drf-renderer-xlsx

Then add the following to your REST_FRAMEWORK settings:

    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 the Content-Disposition header. If no filename is provided, it will default to export.xlsx. For example:

from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.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'

Configuring Styles

Styles can be added to your worksheet header, column header row, and body rows, from view attributes header, column_header, body. Any arguments from the openpyxl library can be used for font, alignment, fill and border_side (border will always be all side of cell).

class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    queryset = MyExampleModel.objects.all()
    serializer_class = MyExampleSerializer
    renderer_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 methods get_body, get_header, get_column_header.

def get_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 add color field to your serializer and fill body rows.

class ExampleSerializer(serializers.Serializer):
    color = serializers.SerializerMethodField()

    def get_color(self, instance):
        color_map = {'w': 'FFFFFFCC', 'a': 'FFFFCCCC'}
        return color_map.get(instance.alarm_level, 'FFFFFFFF')

Release Notes

0.3.2

  • Add supported for nested values; flattens sub-values into sub.value1, sub.value2, etc.

0.3.1

  • Fix an error when an empty result set was returned from the endpoint. Now, it will properly just download an empty spreadsheet.
  • Remove an errant format() function which was removing typing from the spreadsheet.

0.3.0

  • Add support for custom spreadsheet styles (thanks, Pavel Bryantsev!)
  • Add an attribute for setting the download filename instead of export.xlsx per view.

Maintainer

Contributors (Thank You!)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf-renderer-xlsx-0.3.2.tar.gz (7.0 kB view details)

Uploaded Source

Built Distribution

drf_renderer_xlsx-0.3.2-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file drf-renderer-xlsx-0.3.2.tar.gz.

File metadata

  • Download URL: drf-renderer-xlsx-0.3.2.tar.gz
  • Upload date:
  • Size: 7.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.6.7

File hashes

Hashes for drf-renderer-xlsx-0.3.2.tar.gz
Algorithm Hash digest
SHA256 a7149d1c920a9bc0f1a83c532c98d07a69a15ccefdbac363e0c51f80ef76fbde
MD5 cfe042068a786fb184fd1768975b1de0
BLAKE2b-256 5e9ea3db74c381a5fe6d699fd69bb550731d1f2175f0071208753f78590258b3

See more details on using hashes here.

Provenance

File details

Details for the file drf_renderer_xlsx-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: drf_renderer_xlsx-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.6.7

File hashes

Hashes for drf_renderer_xlsx-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9ca353f3e58d2166d219d53e93403df7bdbe12b26a81319cdfe61dc017a57d6e
MD5 054a6b29e9e53559dfc07133a40de57f
BLAKE2b-256 fa2159dceb25ad622be74ea23537215cbf1afb21cdaa34338528eda44d58a080

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page