2017-06-06 131 views
0

我正在使用django import export(DIE)導入一些數據。我在導入數據時遇到問題。Django Excel數據導入導出

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

我想導入所有行。請告訴我如何忽略重複。提前致謝!

+0

@ api55思的指正。 –

回答

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