Quantcast
Channel: Active questions tagged row - Stack Overflow
Viewing all articles
Browse latest Browse all 495

OpenPyXL Duplicate and populate row

$
0
0

I'm trying to copy a row, based upon cell value, and edit the 6th colmn value with the 'VAL' key values.For example row 10 contains "A1"The first column must get the first value of the VAL: A1 (AAA) and the second A1: (BBB).Now it populates the first (and second) with the second BBB value.

I know it's because of the loop that overwrites the first value, but I can't seem to pinpoint the point where to make it skip after the first itteration.

Any help is appreciated!

Please see the sample code:

from openpyxl.utils import rows_from_rangefrom openpyxl import load_workbook# key values:VAL = {'A1': ['AAA', .5, 'BBB', .5],'B1': ['CCC', .333, 'DDD', .333, 'EEE', .333],'C1': ['CCC', .5, 'DDD', .5],'D1': ['FFF', .05, 'BBB', .4, 'AAA', .4, 'EEE', .05, 'GGG', .1],'E1': ['AAA', .5, 'GGG', .5]}def copy_range(range_str, ws, offset, insert_point):""" Copy cell values and style to the new row using offset"""    # Insert empty Row    ws.insert_rows(insert_point, offset)    for row in rows_from_range(range_str):        for cell in row:            dst_cell = ws[cell].offset(row=offset, column=0)            src_cell = ws[cell]            flag = 0            for key in VAL:                if dst_cell.value == key:                    for i in range(int(len(VAL[key]) / 2)):                        flag += 2                        dst_cell.value = list(VAL[key])[flag - 2]            # Populate new Cell value            src_cell.value = dst_cell.valuefile = 'C:/TEMP/TEST/File.xlsx'wb = load_workbook(file)ws = wb[f'Sheet1']# start at row 4for row in ws.iter_rows(4):    for cell in row:        # look at column 6 for key value        if cell.column == 6 and 'A1' in cell.value:            # Get Rownumber to insert            insert_point = cell.row            # Row range to be copied            row_range = f'A{cell.row}:P{cell.row}'            # Offset to the new row            row_offset = 1            # Copy cell values to new row            copy_range(row_range, ws, row_offset, insert_point)    # Save workbook    wb.save(f"{file}--edit.xlsx")

Viewing all articles
Browse latest Browse all 495

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>