Copy a worksheet from one excel file to another

1

Hello, good morning, I have the following code.

from openpyxl import load_workbook
from openpyxl import Workbook

wP =load_workbook(r'C:\Users\Arrontec\Desktop\Automatizacion\Request1_2.xlsx')
wB =load_workbook(r'C:\Users\Arrontec\Desktop\Automatizacion\Request1_1.xlsx')

wPs = wP.get_sheet_by_name('Sheet1')
wBs = wB.get_sheet_by_name('here')

counter = 0
new_rows = []
for rrow in wPs.iter_rows():
    new_rows.append([])
    for cell in rrow:
        new_rows[counter].append(cell.value)
    counter +=1
for wrow in new_rows:
    wBs.append(wrow)

wB.save('Request1_1.xlsx')

But in this case, using append adds it to the end, as you might add it to the beginning of the file.

I would greatly appreciate the help, or some idea that could be given to me. I've been having this problem for some time.

    
asked by Carlos Arronte Bello 27.02.2017 в 16:42
source

1 answer

1

Before editing the question what you wanted was to copy the data from one sheet to another, replacing the corresponding cells and leaving the rest unmodified (a kind of update of part of a sheet with data of other). If you still want to do this you can do it by iterating over each cell of the source sheet and substituting the value of the corresponding cell in the destination sheet using the coordinates of each cell of origin:

from openpyxl import load_workbook


wP =load_workbook(r'C:\Users\Arrontec\Desktop\Automatizacion\Request1_2.xlsx')
wB =load_workbook(r'C:\Users\Arrontec\Desktop\Automatizacion\Request1_1.xlsx')

wPs = wP.get_sheet_by_name('Sheet1')
wBs = wB.get_sheet_by_name('here')

for rrow in wPs.iter_rows():
    for cell in rrow:
        wBs[cell.coordinate] = cell.value

wB.save('Request1_1a.xlsx')
    
answered by 27.02.2017 / 19:06
source