简体   繁体   中英

Copy column of cell values from one workbook to another with openpyxl

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?

Lets say you want to copy the column starting in cell 'A1' of 'Sheet1' in wb3:

wb3 = load_workbook('C:\\folder\\output.xlsx')
ws3 = wb3['Sheet1']

for counter in range(len(DateColumnA)):
    cell_id = 'A' + str(counter + 1)
    ws3[cell_id] = DateColumnA[counter]

wb3.save('C:\\folder\\output.xlsx')

I ended up getting this to write the list to another pre-existing spreadsheet:

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.

I figured out a more concise way to write the source data to a different starting row on destination sheet in a different workbook. I do not need to dump the values in to a list as I did above. iter_rows does all the work and openpyxl nicely passes it to a different workbook and worksheet:

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:\\folder\\DestFile.xlsx')

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