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

2024-03-29 02:06:12 发布

您现在位置:Python中文网/ 问答频道 /正文

Python with Excel:如果列中的一个单元格包含字符串,则返回右边三个单元格的单元格值

正在尝试使用Python脚本来:

  1. 浏览excel工作簿
  2. 查看指定的列
  3. 如果列包含字符串,即“daily sales”
  4. 返回三列上的单元格值

即:如果e列在E25处包含“字符串”,则返回H25中的单元格值

我在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)

E列与第4列相对应

我能够使用上述方法返回E列中的所有值


Tags: columns文件字符串脚本withexcelsheetworkbook
1条回答
网友
1楼 · 发布于 2024-03-29 02:06:12

下面是您问题中概述的步骤的一个非常直观的实现。它使用工作表^{}方法在目标列值中迭代查找目标字符串,如果找到目标字符串,则假定找到了,它使用offset()单元格方法访问所需的单元格值。否则它将引发一个异常。Cell类的方法在openpyxl.cell.cell模块中,并有文档记录here。感谢查理·克拉克向我指出了这一点

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

显示的打印结果来自于在我为测试目的创建的以下example-workbook.xlsx文件上运行它:

screenshot of excel file

相关问题 更多 >