简体   繁体   中英

Openpyxl changing a cell value and copying the row below

I would like to find cells which contain value1|value2 so that I can remove |value2 from that cell and make a copy of the row where value1 was right below it.

For example if a row contains: value0 value1 value2 values3|values33 values4 I would then insert a new row below which would be value0 value1 value2 values33 values4 and the original row would be changed to value0 value1 value2 values3 values4 .

So far I have managed to find the cells which contain | but do not know how to progress further.

In conclusion I'd like to know : How can I edit the cell upon finding the match and copy a row below it with the applied change while also applying a change to the current row so that it no longer contains that value.

from openpyxl import load_workbook

wb = load_workbook('file.xlsx')
sheet = wb['Sheet1']

s = '|'

for row in sheet.iter_rows():
    for cell in row:
        if s in str(cell.value):
            print(cell.value)

Output:

value1|value2
value3|value4
...

IIUC, here is a solution using pandas

import pandas as pd
#Read excel file
df = pd.read_excel('duplicate.xlsx')
for c in df.columns:
    #for each column check if it contains required character
    dd = df[df[c].str.contains('|', regex=False)]
    if len(dd) > 0:
        #If contains iterate the rows
        for i, row in dd.iterrows():
            #Split the cell value by character
            vals = row[c].split('|')
            #Check if the resultant list has more than one value
            if len(vals) > 1:
                #Create a new data frame for the number of resultant values
                dd = pd.DataFrame([row]*(len(vals)))
                rows = len(dd)
                roc = 0
                #replace the values
                for v in vals:
                    dd[c].iloc[roc] = v
                    roc += 1
                #append the new dataframe to the main data frame
                df = df.append(dd)
        #Finally remove the rows that contains character from the column in iteration
        df = df[~df[c].str.contains('|', regex=False)]

Excel input:

在此处输入图片说明

Output:

在此处输入图片说明

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