xlrd 单元格值 returns 错误

xlrd cell value returns error

我有一个具有以下结构的电子表格(数据从 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 returns 工作表中的行数,因此访问最后一行需要:

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)