简体   繁体   English

Excel:如何在包含字符串的列中查找单元格并在另一列行中返回单元格的值?

[英]Excel: How to find cell in a column that contains a string and return value of a cell in another column of row?

Python with Excel: If a cell in a column contains string, return cell value three cells over to the right. Python 与 Excel:如果列中的单元格包含字符串,则返回单元格值向右移动三个单元格。

Trying to come up with a Python script to:试图想出一个 Python 脚本来:

  1. look through an excel workbook翻阅excel工作簿
  2. look through a specified column查看指定的列
  3. if the column contains a string, ie 'daily sales'如果该列包含字符串,即“每日销售额”
  4. return the cell value three columns over返回三列以上的单元格值

ie: If Column E contains 'string' at E25, return the cell value in H25.即:如果 E25 列 E 包含“字符串”,则返回 H25 中的单元格值。

I tried the following in python with excel file living in the same directory as my python file:我在 python 中尝试了以下操作,excel 文件与我的 python 文件位于同一目录中:

import openpyxl

wb = openpyxl.load_workbook('example-workbook.xlsx')
sheet = wb.activelist(sheet.columns)[1]

for cellObj in list(sheet.columns)[4]:
    print(cellObj.value)

Column E corresponds with column 4. E 列对应于第 4 列。

I'm able to return all values in Column E using the above.我可以使用上述方法返回 E 列中的所有值。

Here's a very literal implementation of the steps outlined in your question.这是您问题中概述的步骤的非常字面的实现。 It makes use of the worksheet iter_cols() method to iterate through the target column values looking for the target string and when if finds it—assuming it does—it uses the offset() cell method to access the desired cell value.它使用工作表iter_cols()方法遍历目标列值以查找目标字符串,如果找到它(假设找到了),它使用offset()单元格方法访问所需的单元格值。 Otherwise it raises an exception.否则会引发异常。 The methods of the Cell class are in the openpyxl.cell.cell module and documented here . Cell类的方法位于openpyxl.cell.cell模块中,并记录在此处 Kudos to @Charlie Clark for pointing it out to me.感谢@Charlie Clark 向我指出这一点。

import openpyxl
from openpyxl.utils.cell import column_index_from_string

class NotFoundError(LookupError):
    ''' Exception raised if target string isn't found. '''
    def __init__(self, target_string, column, excel_filepath):
        self.target_string = target_string
        message = (f'{target_string!r} target string not found in column '
                   f'{column!r} of Excel file {excel_filepath!r}')
        super().__init__(message)


def get_offset_column(excel_filepath, column, target_string, offset):
    ''' Search column of specified workbook for target string and return value of
        cell offset a given number of columns from that one.
    '''
    wb = openpyxl.load_workbook(excel_filepath)
    ws = wb.active
    column_index = column_index_from_string(column)

    # Look through the cells of the specified column.
    # If a cell contains target string, return value of the cell at offset column.
    cells = next(ws.iter_cols(min_col=column_index, max_col=column_index)) # Only one col.
    for cell in cells:
        if cell.value == target_string:
            return cell.offset(column=offset).value
    else:
        raise NotFoundError(target_string, column, excel_filepath)


if __name__ == '__main__':
    result = get_offset_column('example-workbook.xlsx', 'E', 'daily sales', 3)
    print(result)  # -> 42

The printed result shown was from running it on the following example-workbook.xlsx file I created for testing purposes:显示的打印结果是在我为测试目的创建的以下example-workbook.xlsx文件上运行的:

excel文件截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在包含字符串的列中查找单元格并在另一行中返回单元格的值? - How to find cell in a column that contains a string and return value of a cell in another of row? 在Pandas数据帧中查找任何单元格值= = x,并返回单元格值,列标题,行和相邻单元格值 - Find any cell values >= x in Pandas dataframe and return cell value, column header, row and neighbouring cell value 如何检查 dataframe 列是否包含来自另一个 dataframe 列的字符串并返回 python Z3A0524F883225EFFA94 中的相邻单元格 - How do I check if dataframe column contains a string from another dataframe column and return adjacent cell in python pandas? 如何使用用户输入来选择行列和返回单元格值? - How to use user input to select row column and return cell value? 如何返回某个值的单元格的列和行索引 - How to return column&row index of cell of certain value 如何在Excel工作表中查找值,然后使用openpyxl在同一行的不同单元格中写入另一个值 - How to find a value in excel sheet and then write another value in a different cell in the same row with openpyxl 如何使用python在excel中一起获取单元格的行值和列值(日期) - How to get the row value and column value(date)together of a cell in excel using python 我如何根据列单元格值和 append 查找一个 dataframe 上的一行到另一个 dataframe 上的一行? - How do i lookup a row on one dataframe based on the column cell value and append that to a row on another dataframe? Pandas:如果同一行上的另一个单元格包含字符串,则将变量设置为单元格中的值 - Pandas: Set variable to value in cell, if another cell on same row contains string 熊猫数据框问题。 创建列,其中行单元格获取另一个行单元格的值 - Pandas dataframe problem. Create column where a row cell gets the value of another row cell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM