Write Excel XSLR with Django

- Andrés Cruz

En español
Write Excel XSLR with Django

To write to an excel, we are going to use the following package:

$ pip install XlsxWriter

It is important to note that this package is for Python and not specific to Django.

We will use the following function to generate an excel document:

excel\views.py

from django.shortcuts import render

import xlsxwriter

def excel_writer(request):
    filename="documents/LibroExcel.xlsx"

    data=[
        ["Nombre","Apellido","Edad"],
        ["Jon","Snow",33],
        ["Daenerys","Targaryen",25],
        ["Tyrion","Lannister",40],
        ["Jaime","Lannister",35],
        ["Cersei","Lannister",36]
    ]

    workbook = xlsxwriter.Workbook(filename)
    worksheet = workbook.add_worksheet("Book 1")

    for row in range(len(data)):
        for col in range(len(data[row])):
            worksheet.write(row, col, data[row][col])

    workbook.close()

    return render(request, 'csv.html')

Explanation of the above code

To generate an excel, it is necessary to indicate the location (filename) and the data (data); in this opportunity, the data is represented in a matrix, since the write() function that allows writing in excel, receives the position of the row, column and data; and it is easier to represent them this way.

To work with excel, the first thing we have to do is generate the file or workbook:

workbook = xlsxwriter.Workbook(filename)

And a worksheet:

worksheet = workbook.add_worksheet("Hoja 1")

This function optionally receives the name you want to give the sheet, in this case “Hoja 1”.

For the rest, the only thing we do is go through the matrix, write in the excel and close it; we will get:

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.