如何将数据从excel解析为模型?

时间:2022-02-06 06:27:33

I parsed excel and get row data in list. It is like

我解析了excel并获取列表中的行数据。它像是

[empty:'', text:’1', text:’1’, text:’40’, text:'']
[empty:'', text:’2’, text:’5’, text:’23’, text:’●’]
[empty:'', text:’3’, text:’9’, text:’52’, text:'']

My excel(data.xlsx) is 如何将数据从excel解析为模型?

我的excel(data.xlsx)是

so list output is ok.Now I wanna put this list to model(User). User model in models.py is

所以列表输出是ok.Now我想把这个列表放到模型(用户)。 models.py中的用户模型是

class User(models.Model):
    user_id = models.CharField(max_length=200)
    name_id = models.CharField(max_length=200)
    age = models.CharField(max_length=200)
    man = models.BooleanField()

The last code of man = models.BooleanField() means man or woman,if ’●’ in excel,it means the user is man and true wanna be put in man variable. Now views.py is

man = models.BooleanField()的最后一个代码意味着男人或女人,如果在excel中的'●',则意味着用户是man而true是想放在man变量中。现在views.py是

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

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

    for row_index in range(sheet.nrows):
        row = sheet.row(row_index)  
        print(row) 
  # I had to add codes connect controller & model

I do not know how to send these list data to model and model has these data.Strictly speaking,I wanna write these list data to sqlite3.Is this code

我不知道如何将这些列表数据发送到模型和模型有这些数据。严格来说,我想把这些列表数据写入sqlite3.Is这段代码

import app.models
for x in row:
  User.user_id = row[1]
  User.name_id = row[2]
  User.age = row[3]
  User.man = row[4]

good way to write model?(or is it wrong way?) Is there other more efficient way to do it?

写模型的好方法?(或者是错误的方式?)还有其他更有效的方法吗?

1 个解决方案

#1


0  

Assuming you have the whole row and columns thing right, this should work:

假设你有完整的行和列的东西,这应该工作:

for row in rows:
  # if the man column is not empty, we assume it's a male:
  is_man = row[4] != ""
  user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man)
  user.save()

#1


0  

Assuming you have the whole row and columns thing right, this should work:

假设你有完整的行和列的东西,这应该工作:

for row in rows:
  # if the man column is not empty, we assume it's a male:
  is_man = row[4] != ""
  user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man)
  user.save()