Django How to Use django-import-export
The django-import-export library supports multiple formats, including xls, csv, json, yaml, and all other formats
Installation
pip install django-import-export
Update your settings.py:
INSTALLED_APPS = (
...
'import_export',
) models.py
#models.py from django.db import models class Member(models.Model): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) email = models.EmailField(blank=True) birth_date = models.DateField() contact = models.CharField(max_length=100, blank=True) class Meta: db_table = "web_member"resources.py
#resources.py from import_export import resources from myapp.models import Member class MemberResource(resources.ModelResource): class Meta: model = MemberDjango Admin
use ImportExportModelAdmin instead of ModelAdmin. admin.py
#admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from myapp.models import Member @admin.register(Member) class MemberAdmin(ImportExportModelAdmin): list_display = ("firstname", "lastname", "email", "birth_date") pass
#urls.py from django.contrib import admin from django.urls import path from myapp import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), #path('',views.index), url(r'^export-exl/$', views.export, name='export'), url(r'^export-csv/$', views.export, name='export'), ]Views.py
#views.py from django.shortcuts import render, redirect from django.http import HttpResponse from myapp.resources import MemberResource def export(request): member_resource = MemberResource() dataset = member_resource.export() #response = HttpResponse(dataset.csv, content_type='text/csv') #response['Content-Disposition'] = 'attachment; filename="member.csv"' #response = HttpResponse(dataset.json, content_type='application/json') #response['Content-Disposition'] = 'attachment; filename="persons.json"' response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' return response