我正在尝试自动化 Excel 中使用包含功能的查找功能。我想确定一个值是否存在于文本字符串中。例如描述字段。如果它发现单元格包含单元格内的值,那么我希望添加在 H 列中找到的代码。我不是在寻找完全匹配,因为 searchName 应该只是数据框中值的一小部分。一切都已启动并运行,但 H 列中的所有值均指示为未找到。我在下面包含了我的代码。
import openpyxl
import pandas as pd
# Load the workbook
wb = openpyxl.load_workbook('C:/Code/Python/List of Parts in SAP.xlsx')
sheet = wb['Parts']
# Read the data from the specified sheet and column
df = pd.read_excel('C:/Code/Python/List of Parts in SAP.xlsx', sheet_name='BE01', usecols=['Description'])
#print(df)
# Iterate over rows and update the 'Found' or 'Not Found' value
for rowNum in range(1, sheet.max_row + 1):
searchName = sheet.cell(row=rowNum, column=1).value
if searchName in df['Description'].values:
sheet.cell(row=rowNum, column=8).value = 'Found'
else:
sheet.cell(row=rowNum, column=8).value = 'Not Found'
# Save the updated workbook
wb.save('updated List of Parts in SAP.xlsx')
我尝试过改变
searchName = sheet.cell(row=rowNum, column=2).value
到
searchName in sheet.cell(row=rowNum, column=2).value
但这会导致
NameError: name 'searchName' is not defined
。我还尝试将 searchName 定义为字符串,认为可能数据类型不相同,这就是为什么所有结果都未找到。
我尝试运行你的代码,它似乎工作正常。 由于你没有提供Excel文件的内容,所以我自己制作了它。 我认为您需要在 for 循环中打印 'searchName' 和 df['Description'].values 并从中获取提示。