Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

excel - python Search a string in a column, and return another column value from that same row

I am currently trying to write a script that will evaluate a spreadsheet to search column A for a string, and then once it finds that string, print the value of column I in the same row. So far I have the following code but it isn't getting me very far.

any help will be appreciated.

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,)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Question: search column A for a string, and then once it finds that string, print the value of column I in the same row

Note: As my 'text.xlsx' uses Column 'C' with "keyX" and doesn't have a Column 'I', I use 'C' and 'D' instead of 'A' and 'I' as requested.

Worksheet in 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))

Qutput:

Found:A3 B3 key2 200, the value of Column D is 200


Usage with other range examples:

Search the whole sheet

cellsOfFoundRow = FindXlCell(search_str)
  

Starting with Row 2 and match only on Column 3 == 'C':

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

Limit the Range from Row 2 to Row 3:

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

It's also posible to use 'ws.iter_cols(...' or any other function that will return a squared_range:

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

Tested with Python:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...