Categories
Django

Getting started with xlsxwriter and Django

Install xlsxwriter

#pip install XlsxWriter

Or follow instructions here: https://xlsxwriter.readthedocs.io/getting_started.html

Imports

import io
from xlsxwriter.workbook import Workbook
from django.http import HttpResponse

views.py


def download_excel_view(request, object_id):
    object = Model.objects.get(object_id=object_id)
    
    output = io.BytesIO()

    workbook = Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet()
    
    worksheet.write(0, 0, 'Hello, world!')
    workbook.close()

    output.seek(0)

    response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = "attachment; filename=excelsheetname.xlsx"

    output.close()

    return response

urls.py

from django.urls import path
from . import views

app_name = "excelwriter"

urlpatterns = [
    ### other views
    path("download-excel-sheet", views.download_excel_view, name="download_sheet"),
]

Template HTML

<a href="{% url 'excelwriter:download_sheet' object_id %}" >
    <button class="btn btn-lg btn-dark button" style="width:100%">
    <span>Download Turnover Doc</span></button> </a>