python搜索列中的字符串,并从该行返回另一个列值

时间:2016-07-07 16:57:50

标签: python excel openpyxl

我目前正在尝试编写一个脚本,用于评估电子表格以在A列中搜索字符串,然后在找到该字符串后,在同一行中打印第I列的值。到目前为止,我有以下代码,但它并没有让我走得很远。

任何帮助将不胜感激。

import openpyxl
wb = openpyxl.load_workbook("2016_SF.xlsx", data_only=True)
ws = wb["161226-161228"]
last_r=70
search_str = raw_input("What plant are you looking for? > ")
last_r = cell.row


def FindXlCell(search_str,last_r):
    for row in ws.iter_rows(row_offset=last_r):
        for cell in row:
            if (search_str == cell.value):
                print(search_str, last_r, cell.row,)

1 个答案:

答案 0 :(得分:1)

  

问题:在A列中搜索一个字符串,然后找到该字符串,则在同一行中打印I列的值

     

注意:由于我的“ text.xlsx”使用列“ C”和“ keyX”,而没有列“ I”,因此我使用“ C”和“ D”代替按要求提供“ A”和“ I”。

test.xlsx中的工作表:
enter image description here

from openpyxl import load_workbook

def FindXlCell(search_str, range=None):
    """
    Iterate over a given 'range' match 'cell.value' with 'search_str'

    :param search_str: String to find
    :param range: Range to iterate, defaults to whole sheet
    :return: 'None' if no match else 
              all cells from the matching Row as 'list of cell objects'
    """
    global ws

    if not range:
        range = ws.iter_rows() # Defaults to whole sheet

    for tupleOfCells in range:
        for cell in tupleOfCells:
            if (cell.value == search_str):
                return [_tuple[0] for _tuple in ws.iter_cols(min_row=cell.row, max_row=cell.row)]

wb = openpyxl.load_workbook("test.xlsx")
ws = wb.worksheets[0]

# search_str = raw_input("What plant are you looking for? > ")
search_str = "key2"

# Search only Column 'C' == 3, openpyxl is 1-based
cellsOfFoundRow = FindXlCell(search_str, ws.iter_rows(min_col=3, max_col=3))

if cellsOfFoundRow:
    # List cellsOfFoundRow is 0-based, Index of D == 3
    print("Found:{}, the value of Column D is {}"
          .format(" ".join([cell.value for cell in cellsOfFoundRow]),
                  cellsOfFoundRow[3].value))
else:
    print("Could not find '{}' in the given cell range!".format(search_str))
  

数量

     

找到:A3 B3 key2 200,D列的值为200


与其他范围示例一起使用

搜索整张纸

cellsOfFoundRow = FindXlCell(search_str)

从第2行开始,并仅在第3列上匹配 =='C':

cellsOfFoundRow = FindXlCell(search_str, ws.iter_rows(min_row=2, min_col=3, max_col=3))

限制从第2行到第3行的范围。

cellsOfFoundRow = FindXlCell(search_str, ws.iter_rows(min_row=2, max_row=3))

也可以使用'ws.iter_cols(...)或其他任何会返回 squared_range 的函数:

cellsOfFoundRow = FindXlCell(search_str, ws.iter_cols(min_row=2, min_col=3, max_col=3))

使用Python:3.4.2测试-openpyxl:2.4.1-LibreOffice:4.3.3.2