我想解析excel并将数据放入模型中(User)。 我收到了一个错误,
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/xxx/testapp/app/views.py", line 17, in <module>
is_man = row[4] != ""
TypeError: 'Cell' object does not support indexing
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(row_index)
print(row[1])
for row in rows:
is_man = row[4] != ""
user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man)
user.save()
我认为行不是单元格而是列表,所以我真的不明白为什么它被称为'Cell',我应该如何解决这个问题。 我试图修复此问题,因此将行单元格更改为列表,如
for row_index in range(sheet.nrows):
rows = sheet.row(row_index)
rows = list(rows)
print(rows)
但是,同样的错误发生了。我该怎么做才能解决这个问题? 现在,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(row_index)
print(rows[1])
for row in rows:
is_man = rows[4] != ""
user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man)
user.save()
我在print(rows[1])
中看到了数据,所以它是
user_id
1
2
3
所以我只能得到user_id数据。这不是我的理想数据,我想得到每个用户数据
1 1 40 leader
我尝试修复此问题并重写print(rows[1][0])
,因此发生TypeError: 'Cell' object does not support indexing
错误。我该如何做出理想的事情?
当我输出print(rows[4])
时,就像
text:'man'
empty:''
text:'●'
empty:''
答案 0 :(得分:1)
使用sheet.row_values(row_index, start_col_index, end_col_index[option])
代替sheet.row()
,因为sheet.row()会返回Cell
个对象而不是Cell
值。
我希望这会对你有所帮助。