Search code examples
pythonexcelautomationopenpyxl

How to offset a column copy with Openpyxl


I am trying to copy columns from one excel workbook to another, here is where I'm at rn :

from openpyxl import load_workbook

wb = load_workbook('220526 MA V3.0.1 John Cpath Right Point list.xlsx')

wb2 = load_workbook('OC PATH.xlsx')


ws_1 = wb['Point List']
ws_2 = wb2 ['OC Point List']

for src, dst in zip(ws_1['B:B'], ws_2['B:B']):
    dst.value = src.value 
    
wb.save(filename = '220526 MA V3.0.1 John Cpath Right Point list.xlsx')
wb2.save(filename = 'OC PATH.xlsx')

It's working fine as long as I only want to copy one column, because when I try to copy column C I get a read only error because my first four rows are merged ad they need to be this way. What I'm trying to do is having this code running from row=4 to last row instead of row 1, but I can't find a working solution.

Sorry in advance if this question is dumb, I'm just getting started in Python. Thanks in advance to whoever will take a few minutes to help me, have a good day!


Solution

  • Try changing the For loop part to something like this

    for row in range (1,ws_1.max_row):
        ONE_CELL = ws_1["C" + str(row)].value # assuming you want to copy from ws_1
        ws_2["C" + str(row)].value = ONE_CELL # assuming you want to paste to row C
    wb2.save("anything you like.xlsx")
    

    Hopefully, if I understood your question correctly, you got your answer.

    Also, don't need to save the workbook that you are coping from ;)