IndexError:列表索引超出范围,我不使用列表索引

时间:2017-09-08 01:36:24

标签: python django excel

我想解析excel并将数据放入模型中(User)。我在views.py中写道

import xlrd

book = xlrd.open_workbook('excel1.xlsx')
sheet = book.sheet_by_index(0)

cells = [
    ('user_id', 0, 5),
    ('name', 3, 1),
    ('nationality', 3, 2),
    ('domitory', 3, 3),
    ('group', 3, 4)]

user1 = {key:sheet.cell_value(rowy, colx) for key, rowy, colx in cells}

print(user1)

Excel是 excel

在这种情况下,domitory为空。我运行此代码,因此发生错误

IndexError: list index out of range
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/XXX/testapp/app/views.py", line 112, in <module>
    user1 = {key:sheet3.cell_value(rowy, colx) for key, rowy, colx in cells}
  File "/Users/XXX/testapp/app/views.py", line 112, in <dictcomp>
    user1 = {key:sheet3.cell_value(rowy, colx) for key, rowy, colx in cells}
  File "/Users/XXX/myenv/lib/python3.5/site-packages/xlrd/sheet.py", line 415, in cell_value
    return self._cell_values[rowx][colx]

我无法理解为什么会发生这种错误,因为我没有编写代码被访问到索引列表之外。但我该如何解决这个问题?我该怎么写呢?

我通过查看答案来编写代码,但是有些错误发生了 enter image description here

1 个答案:

答案 0 :(得分:0)

尝试检查单元格是空白还是空,然后再尝试获取它的值。我从来没用过xlrd所以我不知道这是不是问题:

user1 = {key:sheet.cell_value(rowy, colx) if sheet.cell_type(rowy, colx) not in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK) else key:None for key, rowy, colx in cells}