【问题标题】:How to iterate over a Row or Column of an Excel sheet using Python and look for specific value in cells?如何使用 Python 遍历 Excel 工作表的行或列并在单元格中查找特定值?
【发布时间】:2020-01-30 06:24:00
【问题描述】:

下面是我从某人那里复制的代码。它读取并更新现有的 Excel 文件。我想要的是添加另一个迭代每一行或每一列的功能并寻找一个特定的值。然后我想用一个新值更新那个特定的单元格。

import xlwt
import xlrd
from xlutils.copy import copy

rb = xlrd.open_workbook("imtiaz.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
w_sheet.write(0,1,45)


w_sheet.write(1,1,46)
wb.save("imtiaz.xls")

【问题讨论】:

    标签: python excel xlrd xlwt


    【解决方案1】:

    您也可以使用以下逻辑。最后data(List of List) 包含所有值。每个内部列表代表行。

    import xlrd
    book = xlrd.open_workbook('test.xlsx')
    sheet = book.sheet_by_index(0)
    data = []
    for row in range(0, sheet.nrows):
        l = []
        for column in range(0, sheet.ncols):
            val = sheet.cell(row, column).value
            l.append(val)
    
        data.append(l)
    
    print(data) 
    

    【讨论】:

      【解决方案2】:

      要遍历 Excel 工作表,您可以使用 xlrd 模块中的 sheet.nrows() 函数。

      import xlrd
      
      workbook = xlrd.open_workbook("my_path") # Opens your file
      sheet = workbook.sheet_by_index(0) # Gets the first sheet
      
      for row in range(sheet.nrows): # Iterates over your sheet
          row_value = sheet.row_values(row)
          if row_value[1] == "my_value":
              print row_value
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-18
        相关资源
        最近更新 更多