xlrd单元格值返回错误

时间:2015-06-17 01:18:17

标签: python excel xlrd

我有一个具有以下结构的电子表格(数据从B列开始.Col A为空)

A   B         C            D
    Name      city        salary
    Jennifer   Boston      100
    Andrew     Pittsburgh  1000 
    Sarah      LA          100
    Grand Total            1200

在将数据加载到数据库之前,我需要使用总计过滤掉该行。

为此,我正在阅读Grand Total:

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

我无法弄清楚上面的语法有什么问题。希望有人在这里发现它为什么会抛出错误。

非常感谢, 蜜蜂

1 个答案:

答案 0 :(得分:1)

我认为你的问题并不是基于零的指数。 @Override public String estadoPedido(List<DetallePedido> lista) { EntityManager em = emf.createEntityManager(); //em.getTransaction().begin(); //Consider using Container managed transactions , // if you do remove this line and the line above, and have //entity manager injected ! String mensage = null; try { for (DetallePedido ped : lista) { detPed.setPedEstado("EN PLAN"); em.merge(detPed); } mensage = "detalle seleccionado"; em.getTransaction().commit; //consider removing this line and use Container managed transactions! } catch (Exception e) { mensage = "Error:/p" + e.getMessage(); } finally{ em.close(); } return mensage; } 返回工作表中的行数,因此访问最后一行需要:

last_row = curr_sheet.nrows

Python中的第一个元素被索引为0,因此列表skip_val = curr_sheet.cell_value(last_row-1, 1) 的第一个元素将是mylist。最后一个元素不是mylist[0],而是mylist[len(mylist)],它应该写为mylist[len(mylist)-1]。因此,您可以编写以下内容:

mylist[-1]