Django: How to Use xlwt to Export an Excel File?

Importing xlwt to export data to an Excel file is a common functionality in our Django applications. This guide demonstrates how to achieve this using the xlwt Python module.
  1. Install xlwt Module

In your Django virtual environment, install the xlwt module:

pip install xlwt
  1. Generate Data Tables in models.py

Create a data model in your Django models:

from django.db import models

class Cientist(models.Model):
    """Scientist model"""
    
    name = models.CharField(verbose_name='Name', max_length=64, unique=True)
    email = models.CharField(verbose_name='Email', max_length=255, blank=True, null=True)
    remarks = models.CharField(verbose_name='Remarks', max_length=255, blank=True, null=True)
  1. Implement the View Method

Create a view function to export data:

import xlwt
from django.shortcuts import render, HttpResponse
from .models import Cientist

def export_cientist(request):
    response = HttpResponse(content_type='application/ms-excel')
    
    response['Content-Disposition'] = 'attachment; filename="scientists.xls"'
    
    # Create a new Excel workbook
    wb = xlwt.Workbook(encoding='utf-8')
    
    # Create a new worksheet
    ws = wb.add_sheet('Scientists')
    
    row_num = 0
    
    # Define styles
    font_style = xlwt.XFStyle()
    font_style.font.bold = True
    
    # Write headers
    columns = ['Name', 'Email', 'Remarks']
    
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)
    
    # Prepare data
    rows = Cientist.objects.values_list('name', 'email', 'remarks')
    
    # Write data
    for row in rows:
        row_num += 1
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)
    
    # Save the workbook
    wb.save(response)
    
    return response
  1. Configure the URL Path

Add the URL path for exporting:

from django.contrib import admin
from django.urls import path
from app1 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('export_scientists/', views.export_cientist, name='export_scientists'),
    path('test/', views.test)
]
  1. Export Functionality for Users

Implement the user interface for exporting:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Export Functionality</title>
</head>
<body>
    <!-- Add this code anywhere to enable export -->
    <a class="export-xls" href="{% url 'export_scientists' %}">Export All Scientists to Excel</a>
</body>
</html>
  1. User Experience

When users click the "Export All Scientists to Excel" link, they will be redirected to the export page and receive a downloadable Excel file containing the scientists' data.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Export Functionality</title>
</head>
<body>
    <a href="/export_scientists/">Click Here to Export</a>
</body>
</html>

After clicking, the user will be redirected to the export page, where the Excel file will be downloaded automatically.

Thẻ: python Django Excel export xlwt

Đăng vào ngày 18 tháng 6 lúc 17:44