Skip to main content

Django queryset Excel extraction

Project description

django-excel-extract

PyPI download month PyPI version Python versions Django Versions

Installation

pip install django-excel-extract

Documentation

django-excel-extract helps you easily export Django model data into an Excel file (.xlsx) with minimal setup.

Features

  • Export any Django model QuerySet to Excel.
  • Customize field output (dates, datetimes, booleans, choices).
  • Exclude specific fields.
  • Set custom formats for dates and booleans.
  • Supports ManyToMany fields.
  • Simple integration into Django views.

Usage

You must use the Excel class to generate and export an Excel file.

Parameters

Excel class require parameters:

  • model (Model) — Django model class to export.
  • queryset (QuerySet) — Django queryset containing the data to export.
  • file_name (str, optional) — Name of the generated file (default: 'file_name').
  • title (str, optional) — Sheet title inside the Excel file (default: 'title).
  • exclude (list[str], optional) — List of field names to exclude from export.
  • date_format (str, optional) — Format string for date fields (e.g., '%d/%m/%Y').
  • date_time_format (str, optional) — Format string for datetime fields (e.g., '%d/%m/%Y %H:%M').
  • bool_true (str, optional) — Text representation for boolean True values (default: 'True').
  • bool_false (str, optional) — Text representation for boolean False values (default: 'False').

ORM

Avaliable ORM methods:

  • .get()
  • .filter()
  • .values()

Examples

models.py

from django.db import models
from enum import Enum
import datetime as dt
import pytz


class StatusReport(Enum):
    PENDING = 'Pending'
    IN_PROGRESS = 'In Progress'
    COMPLETED = 'Completed'
    FAILED = 'Failed'


class TypeReport(models.TextChoices):
    INFO = 'Information', 'Information'
    WARNING = 'Warning', 'Warning'
    ERROR = 'Error', 'Error'


class Priority(models.IntegerChoices):
    LOW = 1, 'Low'
    MEDIUM = 2, 'Medium'
    HIGH = 3, 'High'


def generate_unique_number():
    date_now = dt.datetime.now(pytz.timezone('Europe/London'))
    return int(
        f'{date_now.day}{date_now.month}{date_now.year % 1000}{date_now.hour}{date_now.minute}{date_now.microsecond}'
    )


class Category(models.Model):
    name = models.CharField(max_length=255, verbose_name='Category Name')

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

    def __str__(self) -> str:
        return self.name


class Tags(models.Model):
    name = models.CharField(max_length=255, verbose_name='Tag Name')

    class Meta:
        verbose_name = 'Tag'
        verbose_name_plural = 'Tags'

    def __str__(self) -> str:
        return self.name


class Report(models.Model):
    report_num = models.PositiveBigIntegerField(
        unique=True,
        default=generate_unique_number,
        verbose_name='Report Number',
    )
    type_report = models.CharField(
        max_length=255,
        choices=TypeReport.choices,
        verbose_name='Type of Report',
    )
    priority = models.IntegerField(
        choices=Priority.choices,
        verbose_name='Priority',
    )
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE,
        related_name='report_category',
        verbose_name='Category',
    )
    tag = models.ManyToManyField(
        Tags,
        related_name='report_tag',
        verbose_name='Tags',
    )
    name = models.CharField(max_length=255, verbose_name='Report Name')
    status_report = models.CharField(
        max_length=255,
        choices=[(choice.name, choice.value) for choice in StatusReport],
        verbose_name='Status of Report',
    )
    description = models.TextField(verbose_name='Report Description')
    created_at = models.DateTimeField(
        auto_now_add=True, verbose_name='Creation date'
    )

    class Meta:
        verbose_name = 'Report'
        verbose_name_plural = 'Reports'

    def __str__(self) -> str:
        return f'{self.report_num} - {self.name}'

views.py

from django.shortcuts import render

from app.models import Report, StatusReport, TypeReport
from excel_extract.excel import Excel


def index(request):
    return render(request, 'index.html', {})


def extract_excel(request):
    queryset = Report.objects.all()
    exclude = ['id']

    excel = Excel(
        model=Report,
        queryset=queryset,
        file_name='report',
        title='Report',
        exclude=exclude,
        date_time_format='%d/%m/%Y %H:%M',
    )

    return excel.to_excel()

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

django_excel_extract-0.0.7.tar.gz (6.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_excel_extract-0.0.7-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file django_excel_extract-0.0.7.tar.gz.

File metadata

  • Download URL: django_excel_extract-0.0.7.tar.gz
  • Upload date:
  • Size: 6.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.10

File hashes

Hashes for django_excel_extract-0.0.7.tar.gz
Algorithm Hash digest
SHA256 13e13330f1a58961e083f9185017c79faba72436a3fbf91785c094cb3c51410c
MD5 f3eab495352523070fa4118e8e3e9456
BLAKE2b-256 f9ae8a5654159298bca9e57a246ac83aab5c4ba086d872b1eca50ac34ba937d8

See more details on using hashes here.

File details

Details for the file django_excel_extract-0.0.7-py3-none-any.whl.

File metadata

File hashes

Hashes for django_excel_extract-0.0.7-py3-none-any.whl
Algorithm Hash digest
SHA256 bba224db681d0bc4821ff943772aa67073361c6d7393111259db284584705c12
MD5 902833875197abab0cbe8ebc3d63ace2
BLAKE2b-256 6e7237ebdbc4574fd3fb2cce84463cfbb435c5037eb309284abfd7a519d26399

See more details on using hashes here.

Supported by

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