[英]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 脚本来:
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
文件上运行的:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.