2

I wanna parse excel and put data in the model(User). views.py is

#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(row_index)  
  print(rows[1]) 

for row in rows:
  user = User(user_id=row[1], name_id=row[2], age=row[3], 
              name=rows[4])
  user.save()

Excel is excel

I do not want to put data of row whose user_id & name column is empty.In this case,I do not want to put data of line 5 & 6 .But now, my code is to put all excel data to User model.I cannot understand how to extract excel data and put to model.What should I do to do so?I thought if content of list is empty, the data should be skipped.But list is not separate each content, for example [1,1,40,Tom] can be counted 1 list.

user8563636
  • 163
  • 1
  • 5
  • 12
  • why cant you simply check if that column is empty or not ? – Mehrdad Pedramfar Sep 05 '17 at 13:39
  • @mehrdad-pedramfar i wanna know how to do it.If u write code, how do u write it? – user8563636 Sep 05 '17 at 14:09
  • `print(rows[1]) ` gives you the complete row? Never worked with Excel but I would try `rows[1][0]` or similar. Check out this Post: https://stackoverflow.com/questions/19480449/reading-particular-cell-value-from-excelsheet-in-python . He used `value = worksheet.cell(row, column)` to get the specific value. Next step would be `if value: add row` for two value checks use the `and` keyword – hansTheFranz Sep 05 '17 at 15:32

1 Answers1

0

in your code after getting each row, check if its empty or not. like this :

for row in rows:
     if row[1] != '' and row[2] != '':
          user = User(user_id=row[1], name_id=row[2], age=row[3],name=rows[4])
          user.save()
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59