简体   繁体   中英

How can I copy columns from one excel sheet to another with python using openpyxl Library?

I am new to programming. I am trying to copy columns from one excel sheet to another but I'm having problem with my code as only the last column data is being copied to the destination file. I've attached the code and the result i kept getting.

Jan_2020 ="C:\\Users\\yaxee\\OneDrive\\Desktop\\NBET 
Extraction data\\JANUARY 2020.xlsx"
wb1 = xl.load_workbook(Jan_2020)
ws1 = wb1.worksheets[0]

Extraction_WB ="C:\\Users\\yaxee\\OneDrive\\Desktop\\ExtractionWB.xlsx"
wb2 = xl.load_workbook(Extraction_WB)
ws2 = wb2.worksheets[0]

#copy from wb1
for i in range(4, 34):
    c = ws1.cell(row = i, column = 4)
#paste in ws2
for j in range(3, 33):
    ws2.cell(row = j, column = 4).value = c.value
wb2.save(str(Extraction_WB))

Source sheet: 源表

Destination sheet: 在此处输入图像描述

If I understand your need, you need to put the second loop inside the first loop for copy the whole range of rows. Would this work? Kr.

#copy from wb1
for i in range(4, 34):
    c = ws1.cell(row = i, column = 4)
    #paste in ws2
    for j in range(3, 33):
        ws2.cell(row = j, column = 4).value = c.value
wb2.save(str(Extraction_WB))

You don't need two loops. You are just constantly overriding the value of c until it has the last value of the column.

Then, you simply write that value to all rows of the second sheet.

Instead, use one loop, to read a single value from the current row, and write it to the corresponding row in the second sheet:

for row in range(4, 34):
    #copy from wb1
    c = ws1.cell(row=row, column=4)
    #paste in ws2
    ws2.cell(row=row-1, column=4, value=c.value)

If you have some general transformation between the sheets, a more general approach as follows:

step = 2
read_start_row = 4
write_start_row = 3
amount_of_rows = 30

for i in range(0, amount_of_rows, step):
    #copy from wb1
    c = ws1.cell(row=read_start_row+i, column=4)
    #paste in ws2
    ws2.cell(row=write_start_row+(i/step), column=4, value=c.value)

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