【发布时间】:2017-09-08 01:36:23
【问题描述】:
我想解析 excel 并将数据放入模型(用户)中。我在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)
在这种情况下,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]
我不明白为什么会发生这个错误,因为我没有写代码被访问到索引列表之外。但是我该如何解决这个问题?我应该写什么?
【问题讨论】:
-
您可以尝试捕获该异常并写入 0 或 N/A 而不是打破pythonforbeginners.com/error-handling/…
-
我无法理解你的 cmets。如果我在我的代码中编写你的 cmets,我应该写什么?