使用 openpyxl 查找包含具有特定值的单元格的行

uga*_*a77 5 python excel openpyxl

openpyxl正如您可以想象的那样,我对此完全陌生,当我尝试使用它时,我遇到了非常困难的时期。

我有一个 Excel 报告,其中只包含一张工作表(称为Sheet1). 我想搜索所有单元格中包含特定字符串(在这种情况下为产品名称 ABC)的单元格。

然后我想复制包含具有ABC产品名称的单元格的行中每个单元格的内容。并将每个单元格分配给一个变量。

为了让您更好地了解我要实现的目标,我将举一个例子:

例子

所以在这种情况下,我只会从行中复制单元格:2、4、6(因为只有它们包含ABC产品)。

我已经查过类似的问题和答案,但我不明白(以前从未使用过 Excel)。

Hen*_*Yik 25

There's no need to use the pandas for this.

from openpyxl import Workbook
import openpyxl

file = "enter_path_to_file_here"
wb = openpyxl.load_workbook(file, read_only=True)
ws = wb.active

for row in ws.iter_rows("E"):
    for cell in row:
        if cell.value == "ABC":
            print(ws.cell(row=cell.row, column=2).value) #change column number for any cell value you want
Run Code Online (Sandbox Code Playgroud)


小智 9

from openpyxl import load_workbook

wb = load_workbook("report.xlsx")
ws = wb.active

for row in ws.rows:
if row[4].value == "ABC":
    for cell in row:
        print(cell.value, end=" ")
    print()
Run Code Online (Sandbox Code Playgroud)


小智 8

使用 openpyxl 执行此操作对您来说很重要吗?如果没有,我建议使用熊猫。

    import pandas as pd

    df = pd.read_excel("path_to_excel_file")
    df_abc = df[df["Products"] == "ABC"] # this will only contain 2,4,6 rows
Run Code Online (Sandbox Code Playgroud)

然后:

    for row in df_abc.iterrows():
        # do what you want with the row 
Run Code Online (Sandbox Code Playgroud)