Django导入 - 导出excel数据

时间:2017-06-06 09:13:43

标签: python django django-import-export

我使用django import export(DIE)导入一些数据。我在导入数据时遇到问题。

我的 admin.py

class TestResource(resources.ModelResource):

    class Meta:
            model = Test
            exclude = ('id',)
            import_id_fields = ['VS',]
            skip_unchanged = True

 class TestAdmin(ImportExportMixin,admin.ModelAdmin):

      fieldsets = [
        ('VS',      {'fields':['VS']}),
        ('pool',    {'fields':['pool']}),
        ('pool_port', {'fields':['pool_port']}),
        ('idc',        {'fields':['idc']})
       ]

    list_display = ('VS','pool','pool_port','idc')
    list_filter = ['pool_port']
    search_fields = ['VS','pool','pool_port','idc']
    resource_class = TestResource
admin.site.register(Test,TestAdmin)

我想导入一个excel文件,如:

enter image description here

可是:

enter image description here

我想导入所有行。请告诉我如何忽略重复项。提前谢谢!

2 个答案:

答案 0 :(得分:1)

更改行

skip_unchanged = True

skip_unchanged = False

答案 1 :(得分:0)

好的,我找到了一种导入方法。使用save()导入文件。如果你们有更好的方法,请告诉我〜

代码如下:

import os 
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings")

import django
django.setup()

import xlrd
from Test.models import Test


def input(VS,pool_text,port,idc_text):
    i = Test(
        VS = vs,
        pool = pool_text,
        pool_port = port,
        idc = idc_text
        )
    i.save()

files = xlrd.open_workbook('test.xls')
sh = files.sheet_by_index(0)
n = 0
for i in range(1,sh.nrows):

    vs = sh.cell(i,0).value
    pool_text = sh.cell(i,1).value
    port = sh.cell(i,2).value
    idc = sh.cell(i,3).value
    input(vs,pool_text,port,idc)
    n += 1
print n