python在 excel 中用openpyxl从B列的数据 找对A列所在的行

在excel 有A B两列
B列的 每一个数据 在A列进行搜索,找出 含有A列数据 对应的单元格的 行数

如 知道 B列的0003 在A列的 第4行和 第 15行 存在

openpyxl库如何实现

A列 B列
0001 0001
0002 0002
0003 0003
0004 0004
0005 0005
0006 0006
0007 0007
0008 0008
0009 0009
0010 0010
0011 0011
0012 0012
0013 0013
0003
0004
0005
0007
0008
0008
0009
0011
0012

from openpyxl import load_workbook

# 打开工作簿
workbook = load_workbook('example.xlsx')

# 选择第一个工作表
worksheet = workbook.worksheets[0]

# 遍历B列中的单元格,查找在A列中匹配的单元格的行数
for cell in worksheet['B']:
    # 如果B列的单元格不是空的
    if cell.value:
        # 遍历A列中的单元格
        for row in worksheet.iter_rows(min_row=1, min_col=1, max_row=worksheet.max_row, max_col=1):
            # 如果A列的单元格的值与B列的单元格的值匹配
            if row[0].value == cell.value:
                # 输出匹配的单元格的行数
                print(row[0].row)


代码如下


from openpyxl import load_workbook
# 加载Excel文件
wb = load_workbook('filename.xlsx')
# 获取工作表
ws = wb.active
# 定义要搜索的列
search_column = 'B'
# 定义要查找的列
find_column = 'A'
# 定义要查找的值
find_value = '0003'
# 遍历搜索列
for row in ws.iter_rows(search_column):
    # 获取搜索列的值
    search_value = row[0].value
    # 如果搜索列的值等于要查找的值
    if search_value == find_value:
        # 获取查找列的值
        find_value = ws[find_column + str(row[0].row)].value
        # 打印行号
        print('Row:', row[0].row)

该回答引用ChatGPT

这个代码会遍历 B 列中的所有单元格,并在 A 列中搜索与其对应的单元格。如果找到了对应的单元格,就输出其所在的行号和数据。请注意,上述代码中的 example.xlsx 是示例文件的文件名,你需要将其替换为你自己的 Excel 文件名。

import openpyxl

# 打开 Excel 文件
workbook = openpyxl.load_workbook('example.xlsx')
sheet = workbook.active

# 遍历 B 列数据
for cell in sheet['B']:
    # 在 A 列中搜索
    for row in sheet.iter_rows(min_row=1, max_col=1, max_row=sheet.max_row):
        if cell.value in [r[0].value for r in row]:
            # 找到对应的单元格,输出行号和数据
            print(f"{row[0].row}: {cell.value}")


用提供的测试数据,实现代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pandas as pd

df = pd.read_excel(r'C:\input.xlsx', dtype=str)

print("输入数据:\n", df)

list_a = [e for e in df['A列']]
list_b = [e for e in df['B列'] if str(e) != "nan"]

print(list_a)
print(list_b)

for b in list_b:
    list_p = []
    for i, a in enumerate(list_a):
        if a == b:
            list_p.append(i + 1)
    print(f"B列的 {b} 在A列的 {list_p} 行存在")

打印输出结果如下:

输入数据:
       AB0   0001  0001
1   0002  0002
2   0003  0003
3   0004  0004
4   0005  0005
5   0006  0006
6   0007  0007
7   0008  0008
8   0009  0009
9   0010  0010
10  0011  0011
11  0012  0012
12  0013  0013
13  0003   NaN
14  0004   NaN
15  0005   NaN
16  0007   NaN
17  0008   NaN
18  0008   NaN
19  0009   NaN
20  0011   NaN
21  0012   NaN
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013', '0003', '0004', '0005', '0007', '0008', '0008', '0009', '0011', '0012']
['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010', '0011', '0012', '0013']
B列的 0001A列的 [1] 行存在
B列的 0002A列的 [2] 行存在
B列的 0003A列的 [3, 14] 行存在
B列的 0004A列的 [4, 15] 行存在
B列的 0005A列的 [5, 16] 行存在
B列的 0006A列的 [6] 行存在
B列的 0007A列的 [7, 17] 行存在
B列的 0008A列的 [8, 18, 19] 行存在
B列的 0009A列的 [9, 20] 行存在
B列的 0010A列的 [10] 行存在
B列的 0011A列的 [11, 21] 行存在
B列的 0012A列的 [12, 22] 行存在
B列的 0013A列的 [13] 行存在

Process finished with exit code 0

可以使用 openpyxl 库中的 load_workbook 和 Worksheet 对象来完成该任务。以下是一个示例代码,假设要查找的工作簿名为 example.xlsx,要查找的工作表名为 Sheet1,并且要查找的数据范围为 B1:B10 和 A1:A10:

from openpyxl import load_workbook

# 加载工作簿
workbook = load_workbook(filename='example.xlsx')

# 选择工作表
sheet = workbook['Sheet1']

# 遍历B列的单元格
for cell in sheet['B1:B10']:
    if cell.value == '要查找的数据':
        # 获取A列对应的单元格
        a_cell = sheet[cell.row][0]
        print(a_cell.value)


-
在上面的代码中,我们使用了 sheet['B1:B10'] 来选择要遍历的单元格范围,并使用 cell.value 获取每个单元格的值。如果找到了要查找的数据,我们使用 sheet[cell.row][0] 获取 A 列对应的单元格,其中 cell.row 是找到数据的行号,0 表示 A 列对应的列号。
-
注意:上述代码中默认读取的数据类型是字符串,如果 B 列中存在非字符串类型的数据,需要将 cell.value 转换为相应的类型。

根据要求设计了表格,名称为data,内容为:

img

程序为:

from openpyxl import Workbook, load_workbook

path1 = r'C:\Users\Desktop\data.xlsx'
wb = load_workbook(path1)
ws = wb[wb.sheetnames[0]]  # 选择第一个sheet

columns = tuple(ws.columns)
for cell in columns[1]:
    row = []
    for cell2 in columns[0]:
        if cell2.value == cell.value and cell2.value is not None:
            row.append(int(cell2.coordinate[1:])-1)
    if len(row) != 0:
        print(f'B列的{cell.value}出现在A列的第{row}行')

结果为

B列的0001出现在A列的第[1]B列的0002出现在A列的第[2]B列的0003出现在A列的第[3]B列的0004出现在A列的第[ 4 11]B列的0005出现在A列的第[ 5 12]B列的0006出现在A列的第[ 6 13]B列的0007出现在A列的第[ 7 14]B列的0008出现在A列的第[ 8 15]B列的0009出现在A列的第[9]B列的0010出现在A列的第[10]行

进程已结束,退出代码0

满足要求
如果问题得到解决请点 采纳~~

以下是使用openpyxl库实现搜索A列对应单元格行数的示例代码:

from openpyxl import load_workbook

# 打开Excel文件
wb = load_workbook(filename='example.xlsx', read_only=True)

# 选择第一个工作表
ws = wb.active

# 遍历B列
for cell in ws['B']:
    search_value = cell.value
    if search_value is not None:
        # 遍历A列,查找对应单元格
        for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1, max_col=1):
            if row[0].value == search_value:
                # 输出找到的行号
                print(f'"{search_value}" found in row {row[0].row}')

在上面的示例中,我们打开了名为example.xlsx的Excel文件,并选择了第一个工作表。然后,我们遍历了B列中的每个单元格,并在A列中查找对应的单元格。如果找到,则输出行号。

请注意,该代码假定A列和B列的数据是一一对应的,且B列中的值不重复。如果数据存在重复或非一一对应情况,则需要对代码进行适当修改。

https://blog.csdn.net/shifengboy/article/details/127399836


import openpyxl

# 打开Excel文件
workbook = openpyxl.load_workbook('example.xlsx')

# 选择工作表
sheet = workbook.active

# 遍历B列的每一个单元格
for cell in sheet['B']:
    # 如果B列单元格有数据
    if cell.value:
        # 遍历A列的每一个单元格
        for row in sheet.iter_cols(min_col=1, max_col=1, min_row=1, values_only=True):
            # 如果A列单元格与B列单元格的值相等
            if row[0] == cell.value:
                # 输出该A列单元格的行数
                print(cell.value, "in row:", row[0].row)