在两个Excel工作表中搜索和查找值(从xlrd到openpyxl)

问题描述 投票:0回答:1
wrbk = xlrd.open_workbook("D:Book1.xlsx")
idx = 0

book_1 = xlrd.open_workbook("D:Book2.xlsx")
sh_1 = book_1.sheet_by_name('Sheet4')

i = 0
for x in range(sh_1.nrows):
    i = i + 1
    if i >= sh_1.nrows:
        break
    if sh_1.cell(i, 2).value:
        concat = sh_1.cell(i, 2).value
        for y in range(len(wrbk.sheets())):
            sht = wrbk.sheet_by_index(y)
            for j in range(sht.ncols):
                for cell in range(sht.nrows):
                    list = str(sht.cell(cell, j).value)
                    if list.__contains__(concat):
                        print(sh_1.cell(i, 2).value)

我正在使用此代码在工作簿中查找值,然后在另一个工作簿中搜索该值。我正在使用xlrd,到目前为止的输出还不错,但是我无法使用xlrd进行读写。我需要建议将此代码从xlrd更改为openpyxl。

python excel openpyxl xlrd
1个回答
1
投票

这定义了执行搜索的功能,并使用Regular Expression进行了“包含”匹配。更改打印以适合。

from openpyxl import load_workbook
import re

# open workbook 
excel_file1 = 'D:Book1.xlsx'
wb1 = load_workbook(excel_file1) # wrbk
ws1 = wb1["Sheet1"]

excel_file2 = 'D:Book2.xlsx'
wb2 = load_workbook(excel_file2) # book_1
ws2 = wb2["Sheet4"] # sh_1

# fn to search all sheets in workbook
def myfind(wb,s):
    for ws in wb.worksheets:       
        for c in range(1,ws.max_column+1):
            for r in range(1,ws.max_row+1):
                txt = ws.cell(r,c).value 
                if txt is None:
                    pass
                elif re.search(s,txt):
                    print("Found",s,txt,ws,r,c)

# scan col C
for r in range(1,ws2.max_row+1):
    s = ws2.cell(r, 3).value 
    if s is None: 
        pass
    else: 
        print(r,s)
        myfind(wb1,s)

© www.soinside.com 2019 - 2024. All rights reserved.