Copying Specific Column from One Workbook to Another using Openpyxl

Viewed 1097

I am fairly new to python and trying to copy the data in workbook one, columns A,D,G, paste them into columns A,B,C, on the new workbook. I know how to copy one column or the whole worksheet but can't figure that out.

from openpyxl import load_workbook

wb1 = load_workbook('test1.xlsx')
wb2 = load_workbook('test2.xlsx')

ws1 = wb1.get_sheet_by_name('Sheet1')
ws2 = wb2.get_sheet_by_name('Sheet1')

mr = ws1.max_row
mc = ws1.max_column

for i in range (1, mr + 1):
    for j in range (1, mc + 1):
        c = ws1.cell(row=i, column=j)
        ws2.cell(row=i, column=j).value = c.value


wb2.save('test2.xlsx')

That is the code I am using to copy the whole worksheet

1 Answers

I think you're looking for something like this

for i in range(1, mr + 1):
        ws2['A' + str(i)].value = ws1['A' + str(i)].value
        ws2['B' + str(i)].value = ws1['D' + str(i)].value
        ws2['C' + str(i)].value = ws1['G' + str(i)].value
Related