我有一个具有以下结构的电子表格(数据从 B 列开始。A 列为空)
A B C D
Name city salary
Jennifer Boston 100
Andrew Pittsburgh 1000
Sarah LA 100
Grand Total 1200
在将其加载到数据库之前,我需要过滤掉总计的行。
为此,我将总计解读为:
import xlrd
import pymssql
#open workbook
book = xlrd.open_workbook("C:\_Workspace\Test\MM.xls")
print( "The number of worksheets is", book.nsheets)
#for each row in xls file loop
#skip last row
last_row = curr_sheet.nrows
print(last_row)
print(curr_sheet.ncols)
skip_val = curr_sheet.cell(last_row,1).value
print( skip_val)
if skip_val == "Grand Total":
last_row = last_row - 1
else:
last_row = last_row
for rx in range(last_row):
print( curr_sheet.row(rx))
但是,我收到以下错误:
Traceback (most recent call last): File "C:\_Workspace\Test\xldb.py", line 26, in <module> skip_val = curr_sheet.cell(last_row,1).value File "c:\Python34\lib\site-packages\xlrd-0.9.3- >py3.4.egg\xlrd\sheet.py", line 399, in cell self._cell_types[rowx][colx], IndexError: list index out of range
我无法弄清楚上面的语法有什么问题。希望这里有人能够找出抛出错误的原因。
提前非常感谢, 蜜蜂
最佳答案
我认为你的问题不在于考虑从零开始的索引。 last_row = curr_sheet.nrows
返回工作表中的行数,因此访问最后一行需要:
skip_val = curr_sheet.cell_value(last_row-1, 1)
Python 中的第一个元素的索引为 0,因此列表 mylist
的第一个元素将为 mylist[0]
。最后一个元素不是 mylist[len(mylist)]
,而是 mylist[len(mylist)-1]
,应写为 mylist[- 1]
。因此,您可以编写以下内容:
skip_val = curr_sheet.cell_value(-1, 1)
关于python - xlrd 单元格值返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880815/