Skip to content Skip to sidebar Skip to footer

How To Swap Columns Using Openpyxl

I've .xlsx file. Rows are good, values are just fine. But i need to change the columns order by list of new columns positions, e.g: old = [1, 2, 3, 4] new = [2, 1, 4, 3] Docs are c

Solution 1:

Your current approach risks overwriting cells. I'd be tempted to move the cells from existing columns to new columns in the correct order and then delete the old ones.

for c in ws['A']:
    new_cell = c.offset(column=6)
    new_cell.value = c.value

for c in ws['B']:
    new_cell = c.offset(column=5)
    new_cell.value = c.value

ws.delete_cols(min_col=1, max_col=4)

This is just to give you the general idea could be optimised and parametrised so you could do each row at once.

Or you could use move_range:

ws.move_range(min_col=1, max_col=1, min_row=1, max_row=ws.max_row, cols=5)

In either case be careful not to overwrite existing cells before you've moved them.


Post a Comment for "How To Swap Columns Using Openpyxl"