sheet.nrows有一个错误的值 – python excel文件

我有一个很奇怪的问题 我试图从Excel文件中读取一些数据,但属性nrows有一个错误的值。 尽pipe我的文件有很多行,但它只返回2。

我在pydev eclipse工作。 我不知道究竟是什么问题; 一切看起来不错。

当我尝试手动访问其他行的索引,但我得到了索引错误。

我感谢任何帮助。

如果有帮助,这是我的代码:

 def get_data_form_excel(address): wb = xlrd.open_workbook(address) profile_data_list = [] for s in wb.sheets(): for row in range(s.nrows): if row > 0: values = [] for column in range(s.ncols): values.append(str(s.cell(row, column).value)) profile_data_list.append(values) print str(profile_data_list) return profile_data_list 

为了确保您的文件没有损坏,请尝试使用另一个文件; 我怀疑xlrd是越野车。

另外,我已经清理了你的代码,看起来更好一些。 例如, if row > 0检查是不必要的,因为您可以在第一个位置迭代range(1, sheet.nrows)

 def get_data_form_excel(address): # this returns a generator not a list; you can iterate over it as normal, # but if you need a list, convert the return value to one using list() for sheet in xlrd.open_workbook(address).sheets(): for row in range(1, sheet.nrows): yield [str(sheet.cell(row, col).value) for col in range(sheet.ncols)] 

要么

 def get_data_form_excel(address): # you can make this function also use a (lazily evaluated) generator instead # of a list by changing the brackets to normal parentheses. return [ [str(sheet.cell(row, col).value) for col in range(sheet.ncols)] for sheet in xlrd.open_workbook(address).sheets() for row in range(1, sheet.nrows) ] 

在尝试了一些其他的文件后,我确定它是关于这个文件的,我想这跟Microsoft 2003和2007的差别有关。

我最近也遇到了这个问题。 我试图读取一个Excel文件和由xlrd.nrows给出的行号小于实际的。 正如Zeinab Abbasi所说,我尝试了其他的文件,但是效果很好。

最后,我发现不同之处:在失败的文件中embedded了一个基于VB脚本的button,用于下载和追加logging到当前表单。

然后,我尝试将该文件转换为.xlsx格式,但是它要求我将其另存为另一种启用了macros的格式,例如.xlsm。 这一次xlrd.nrows给出了正确的值。

你的excel文件是否使用外部数据? 我刚刚遇到了同样的问题,并find了解决办法。 我正在使用Excel来从谷歌表获得信息,我想让Python显示我的数据。 所以,对于我的修复是去DATA>连接(在“获取外部数据”)>属性,并取消选中“保存工作簿之前从外部数据范围中删除数据”