Django import / export實現數據庫導入導出


 

使用django-import-export庫,導入導出數據,支持csv、xls、json、html等格式

官網:http://django-import-export.readthedocs.io/en/latest/installation.html

1、安裝django-import-export

pip install django-import-export

2、配置settings.py

 

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'customer',
    'publisher',
    'import_export',
)

 

 

執行命令: python manage.py collectstatic

3、models.py 建立model

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name


class Book(models.Model):
    name = models.CharField('Book name', max_length=100)
    author = models.ForeignKey(Author, blank=True, null=True)
    author_email = models.EmailField('Author email', max_length=75, blank=True)
    imported = models.BooleanField(default=False)
    published = models.DateField('Published', blank=True, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)

    def __unicode__(self):
        return self.name

 

4、在admin.py 創建Resource、對應的Admin

from import_export import resources
from core.models import Book
from import_export.admin import ImportExportModelAdmin


class BookResource(resources.ModelResource):

    class Meta:
        model = Book
        export_order = ('id', 'name', 'author', 'author_email', 'imported', 'click', 'published', 'price', 'categories')

@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
    list_display = ('name', 'author', 'author_email', 'imported', 'published', 'price', 'categories')
    search_fields = ('name', 'author','published')
    date_hierarchy = 'date'   
    resource_class = BookResource

 

export_order:設置導出字段的順序

5、Django界面實現導入導出

 

 

 

自定義導出 方式 action 這種方式也推薦

import xlwt
#導出Excel
from django.http import StreamingHttpResponse
class AdminReport(admin.ModelAdmin):
    actions = ["saveexecl"]                 # 自定義的action(導出到excel表格)
    list_display = ("id",'offer','day_time', 'idfa', 'submit_result_text', 'callback_result_text')    # 顯示的列
    search_fields = ('day_time','callback_result_text')      # 可以搜索的字段
    date_hierarchy = 'day_time'      # 按照日期顯示
    list_filter = ('offer',)         # 過濾條件
    list_per_page = 500              # 每頁顯示500條,太多了可能會出現服務器崩掉的情況
    
    def saveexecl(self,request,queryset):
        Begin = xlwt.Workbook()
        sheet = Begin.add_sheet("response")
        cols = 0
        for query in queryset:
            # you need write colms                     # 好像有個方法可以一次性寫入所有列,記不清了,只能用這種簡單的方法去實現
            sheet.write(cols,1,str(query.idfa))        # 寫入第一列
            sheet.write(cols,2,str(query.day_time))    # 寫入第二列
            sheet.write(cols,3,str(query.keyword))     # 寫入第三列
            cols += 1
        Begin.save("%s" %(filename))
        def file_iterator(filename,chuck_size=512):
            with open(filename,"rb") as f:
                while True:
                    c = f.read(chuck_size)
                    if c:
                        yield c
                    else:
                        break
        response = StreamingHttpResponse(file_iterator(filename))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format("result.xls")
        return response
    saveexecl.short_description = "導出Excel"            # 按鈕顯示名字


admin.site.register(Report, AdminReport)     # 注冊到admin

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM