帮助Excel,Python和XLRD

编程相对较新,为什么我select使用Python来学习。

目前,我正试图从XLRD的Excel电子表格中读取用户名,密码列表并使用它们login到某个东西。 然后退出并转到下一行。 login等,继续前进。

这里是代码的一个小窍门:

import xlrd wb = xlrd.open_workbook('test_spreadsheet.xls') # Load XLRD Excel Reader sheetname = wb.sheet_names() #Read for XCL Sheet names sh1 = wb.sheet_by_index(0) #Login def readRows(): for rownum in range(sh1.nrows): rows = sh1.row_values(rownum) userNm = rows[4] Password = rows[5] supID = rows[6] print userNm, Password, supID print readRows() 

我已经得到了variables,并且一次性读取所有variables,这里是我缺乏编程技能的地方。 我知道我需要遍历这些,并与他们做一些事情,但我有什么是最好的做法迷失了。 任何见解都会很棒。

再次感谢你

指针的夫妇:

我build议你不打印你的函数没有返回值,而只是调用它,或返回的东西打印。

 def readRows(): for rownum in range(sh1.nrows): rows = sh1.row_values(rownum) userNm = rows[4] Password = rows[5] supID = rows[6] print userNm, Password, supID readRows() 

或者查看docs您可以从row_values中切片:

row_values(rowx,start_colx = 0,end_colx = None)[#]

 Returns a slice of the values of the cells in the given row. 

因为你只需要索引4 – 6的行:

 def readRows(): # using list comprehension return [ sh1.row_values(idx, 4, 6) for idx in range(sh1.nrows) ] print readRows() 

使用第二种方法从函数中获得列表返回值,可以使用此函数来设置一个variables,其中包含从Excel文件中读取的所有数据。 该列表实际上是包含您的行值的列表的列表。

 L1 = readRows() for row in L1: print row[0], row[1], row[2] 

获得数据后,可以通过遍历列表来操作它,就像上面的打印示例一样。

 def login(name, password, id): # do stuff with name password and id passed into method ... for row in L1: login(row) 

你也可能想看看不同的数据结构来存储你的数据。 如果你需要使用字典来查找用户的名字,可能是你最好的select:

 def readRows(): rows = [ sh1.row_values(idx, 4, 6) for idx in range(sh1.nrows) ] # using list comprehension return dict([ [row[4], (row[5], row[6])] for row in rows ]) D1 = readRows() print D['Bob'] ('sdfadfadf',23) import pprint pprint.pprint(D1) {'Bob': ('sdafdfadf',23), 'Cat': ('asdfa',24), 'Dog': ('fadfasdf',24)} 

有一点需要注意的是,字典值在python中任意sorting。

我不确定你是否打算使用xlrd,但你可能想看看PyWorkbooks(注意,我是PyWorkbooks的编写者:D)

 from PyWorkbooks.ExWorkbook import ExWorkbook B = ExWorkbook() B.change_sheet(0) # Note: it might be B[:1000, 3:6]. I can't remember if xlrd uses pythonic addressing (0 is first row) data = B[:1000,4:7] # gets a generator, the '1000' is arbitrarily large. def readRows() while True: try: userNm, Password, supID = data.next() # you could also do data[0] print userNm, Password, supID if usrNm == None: break # when there is no more data it stops except IndexError: print 'list too long' readRows() 

你会发现,这比你所做的任何事情都快得多(我希望更容易)。 你的方法会得到一整行,可能是一千个元素。 我已经写了这个尽可能快地检索数据(并包括像numpy这样的事情的支持)。

在你的情况下,速度可能不是那么重要。 但是将来可能是:D

一探究竟。 新手用户可以使用该程序的文档。 http://sourceforge.net/projects/pyworkbooks/

似乎是好的。 有一点意见:你应该用“单元格”replace“行”,因为你实际上是从单元格中读取单元格的值