简体   繁体   中英

Search specific text(text pattern) in excel and copy all resulting rows to another sheet in same workbook using openpyxl

I have an excel file with multiple sheets, 3rd column(contains around 500 rows) of sheet3 contains various names. I want to search column 3 for specific text and if it matches then copy the whole row along with the header row to new sheet within same excel.

Issue with "name column" is that most of the text refer to same item but naming convention is different, so: अपर तहसीलदार, नायाब तहसीलदार, नायब तहसीलदार,
अतिरिक्त तहसीलदार

refers to same item but written differently, so for that I have to search for all variants.

I have no prior Python or openpyxl background so what I've got so far is:

import openpyxl
wb = openpyxl.load_workbook(r'C:/Users/Anas/Downloads/rcmspy.xlsx')

#active worksheet data
ws = wb.active

def wordfinder(searchString):
    for i in range(1, ws.max_row + 1):
        for j in range(1, ws.max_column + 1):
            if searchString == ws.cell(i,j).value:
                print("found")
                print(ws.cell(i,j))


wordfinder("अपर तहसीलदार")

It is not showing any error but don't print anything either. The excel sheet looks something like this: 在此处输入图像描述

I'm not certain, but I would suggest something along the lines of:

variants = {'alpha','alfa','elfa'}
data = []
rowCount = 0
for row in ws.values:
    //each row is an array of cells
    if rowCount == 0:
        //header row
        data.append(row)
    elif row[2] in variants:
        data.append(row)
    rowCount += 1

wsNew = wb.create_sheet('Variations')
for line in data:
    wsNew.append(line)

wb.save('newWorkbook.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM