14. Django Python – Export File

django python bahasa indonesia

Export File

  1. Buat file resource.py di dalam folder apps01.
from import_export import resources
from apps.apps01.models import Siswa

class SiswaResource(resources.ModelResource):
    class Meta:
        model = Siswa

2. Buat views.

from django.shortcuts import render, redirect, HttpResponse
from apps.apps01.resource import SiswaResource

def export_xls(request):
   siswa = SiswaResource()
   dataset = siswa.export()
   response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
   response['content-Disposition'] = 'attachment; filename=siswa.xls'
   return response

3. Tambahkan URL.

urlpatterns = [
...
...
    path('export/xls/', export_xls, name='export_xls'),
]

4. Tambahkan button di html.

<a href="{% url 'export_xls' %}" class="btn btn-primary">Export</a>

Kolom yang Ditampilkan

Edit resource.py.

from import_export import resources
from apps.apps01.models import Siswa

class SiswaResource(resources.ModelResource):
    class Meta:
        model = Siswa
        fields = ['nomor','nama_depan','nama_belakang','tgl_lahir','jurusan__nama_jurusan',]

Modify Nama Kolom

Edit resource.py.

from import_export import resources
from apps.apps01.models import Siswa

class SiswaResource(resources.ModelResource):
    jurusan__nama_jurusan = Field(attribute='jurusan', column_name='jurusan')

    class Meta:
        model = Siswa
        fields = ['nomor','nama_depan','nama_belakang','tgl_lahir','jurusan__nama_jurusan']

Urutan Kolom yang Ditampilkan

Edit resource.py.

from import_export import resources
from apps.apps01.models import Siswa

class SiswaResource(resources.ModelResource):
    jurusan__nama_jurusan = Field(attribute='jurusan', column_name='jurusan')

    class Meta:
        ...
        ...
        export_order = ['nama_depan','nama_belakang','nomor','tgl_lahir','jurusan__nama_jurusan']


Lanjutkan Membaca Materi Lengkap


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.