2017-09-06 25 views
0

我想解析excel並將數據放入模型(用戶)中。然而現在,只剩下最後的Excel數據放在模型和數據的數量是4.4是所有的數練成像 excel只有最後一個excel數據放在模型中

行現在db.sqlite3是

|10|Karen||| 
|10|Karen||| 
|10|Karen||| 
|10|Karen||| 

我的理想db.sqlite3是

1|1|Blear|40|false|l 
2|5|Tom|23|true|o 
3|9|Rose|52|false|m 
|10|Karen||| 

所有數據都要放在那裏。 這樣的結果爲什麼會發生? views.py是

#coding:utf-8 
from django.shortcuts import render 
import xlrd 
from .models import User 

book = xlrd.open_workbook('../data/data.xlsx') 
sheet = book.sheet_by_index(1) 

for row_index in range(sheet.nrows): 
    rows = sheet.row_values(row_index) 
    print(rows) 

def build_employee(employee): 
    if employee == 'leader': 
    return 'l' 
    if employee == 'manager': 
    return 'm' 
    if employee == 'others': 
    return 'o' 

for row in rows: 
    is_man = rows[4] != "" 
    emp = build_employee(rows[5]) 
    user = User(user_id=rows[1], name_id=rows[2], name=rows[3], 
       age=rows[4],man=is_man,employee=emp) 
    user.save() 

,當我在print(rows)打印出來行,結果是

Blear 
Tom 
Rose 
Karen 

所以我覺得行了Excel中的所有數據。 models.py是

class User(models.Model): 
    user_id = models.CharField(max_length=200) 
    name_id = models.CharField(max_length=200) 
    name = models.CharField(max_length=200) 
    age = models.CharField(max_length=200) 
    man = models.BooleanField() 
    TYPE_CHOICES = (
    ('m', 'manager'), 
    ('l', 'leader'), 
    ('o', 'others'), 
    ) 
    employee =models.CharField(max_length=1, choices=TYPE_CHOICES) 

我該如何解決這個問題?

+0

只想通過調用'sheet = book.sheet_by_index(1)'來檢查您是否正在訪問圖紙2,如果您想訪問圖紙1,則需要調用'sheet = book.sheet_by_index(0)' – kaza

+0

@bulbus這是好的,因爲我想讀表2。 – user8504021

回答

0

在此塊的末尾rows只有最後一行的值(行與Karen)。

for row_index in range(sheet.nrows): 
    rows = sheet.row_values(row_index) 
    print(rows) 

現在上面後,當你做下面你迭代值的最後一排。還記得你沒有使用row裏面的塊是一個單元格值循環訪問['',10,'Karen','','','']

for row in rows: 
    is_man = rows[4] != "" 
    emp = build_employee(rows[5]) 
    user = User(user_id=rows[1], name_id=rows[2], name=rows[3], 
       age=rows[4],man=is_man,employee=emp) 
    user.save() 

您應該更正如下上述塊..

for row_index in range(sheet.nrows): 
    rows = sheet.row_values(row_index) 
    is_man = rows[4] != "" 
    emp = build_employee(rows[5]) 
    user = User(user_id=rows[1], name_id=rows[2], name=rows[3], 
       age=rows[4],man=is_man,employee=emp) 
    user.save() 

請注意,我沒有適當關注標題行。如果需要,請在您的最後完成。

+0

也應該有六個相同的條目在你的分貝,我很驚訝,只有四個! – kaza

+0

thx,你的答案。我讀了你的答案,但我不明白我應該重寫的地方。我找不到我的代碼和你的區別。我應該在哪裏修復?爲什麼你認爲應該有六個相同的條目?這個用戶(user_id = rows [1],name_id = rows [2],name = rows [3], age = rows [4],man = is_man,employee = emp)的地方?如果你是我,你將如何寫,以避免分貝數錯誤? – user8504021

+0

對不起,我剛剛粘貼了你的代碼,並指出它出錯的地方,我沒有輸入任何更正的代碼。現在我編輯了一下,以便輸入更正的代碼塊。請用'只替換'你的最後一個循環,看看它是否有效。 – kaza

相關問題