Python Forum

Full Version: Need to copy column of cell values from one workbook to another with openpyxl
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am extracting data from one workbook's column and need to copy the data to another existing workbook.

This is how I extract the data (works fine):

wb2 = load_workbook('C:\\folder\\AllSitesOpen2.xlsx')
ws2 = wb2['report1570826222449']
#Extract column A from Open Sites
DateColumnA = []
for row in ws2.iter_rows(min_row=16, max_row=None, min_col=1, max_col=1):
    for cell in row:
        DateColumnA.append(cell.value)
DateColumnA
The above code successfully outputs the cell values in each row of the first column to DateColumnA.

I'd like to paste the values stored in DateColumnA to this existing destination workbook:

#file to be pasted into
wb3 = load_workbook('C:\\folder\\output.xlsx')
ws3 = wb3['Sheet1']
But I am missing a piece conceptually here. I can't connect the dots. Can someone advise how I can get this data from my source workbook to the new destination workbook? Thanks!
Thanks I saw that article but it didn't use iter_rows and iter_cols, which I was determined to use. Anyway, I figured out this solution:

for x, rows in enumerate(DateColumnA):
    ws3.cell(row=x+1, column=1).value = rows
    #print(rows)
    wb3.save('C:\\folder\\output.xlsx')
Works great but now I need to determine how to write the data to output.xlsx starting at row 16 instead of row 1 so I don't overwrite the first 16 existing header rows in output.xlsx. Any ideas appreciated.
Figured out how to write the source data to a different starting row on destination sheet. I do not need to dump the values in to a list as I did above:

row_offset=5
for rows in ws2.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):
    for cell in rows:
        ws3.cell(row=cell.row + row_offset, column=1, value=cell.value)
        wb3.save('C:\\folder1\\DestFile.xlsx')