如何使用XLRD获取某一行中某列的值

时间:2015-04-20 14:58:25

标签: python xlrd

我正在尝试遍历电子表格并获取某列下某行中的单元格值,如下所示:

# Row by row, go through the originalWorkSheet and save the values from the selected columns
numberOfRowsInOriginalWorkSheet = originalWorkSheet.nrows - 1
rowCounter = 0
while rowCounter <= numberOfRowsInOriginalWorkSheet:
    row = originalWorkSheet.row(rowCounter)
    #Grab the values in certain columns, say with the 
    # column name "Promotion" and save them to a variable

这可能吗?我的google-foo在这一次失败了。 谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点,看看docs

这样的事情:

promotion_col_index = <promotion column index>

list_of_promotion_cells = originalWorkSheet.col(promotion_col_index)

list_of_promotion_values = [cell.value for cell in list_of_promotion_cells]

将为您提供&#34;促销&#34;中的值列表柱

答案 1 :(得分:1)

最简单的方法:

from xlrd import open_workbook


book = open_workbook(path_to_file)
sheet = book.sheet_by_index(0)
for i in range(1, sheet.nrows):
    row = sheet.row_values(i)
    variable = row[0]  # Instead zero number of certain column

或者您可以循环行列表并打印每个单元格值

book = open_workbook(path_to_file)
sheet = book.sheet_by_index(0)
for i in range(1, sheet.nrows):
    row = sheet.row_values(i)
    for cnt in range(len(row)):
       print row[cnt]

希望这有帮助