简体   繁体   中英

Copy column to another sheet in Python

I've been trying to copy a variable length column to another sheet through openpyxl. What I'm looking to do is copy, for example, column B from row 2 up to row = sheet.max_row and paste it into another sheet within the same workbook. Specifying the first cell in the sheet in which it will start pasting in would be nice too.

I've tried following this tutorial (copy and paste cell ranges into another workbook) to no avail.

So far I have my code set up like this:

import openpyxl
wb = openpyxl.load_workbook('workbook1.xlsx')
wb.create_sheet('sheet2') # this is where I want the cells to be pasted into
sheet = wb['sheet1'] # name of the sheet that is being analyzed


wb.save('workbook1.xlsx') # 

Does anyone have any code that could help? If not, what resources are available to look at for information on how to solve this problem?

ws1 = wb.active # source
ws2 = wb['sheet2'] # destination

for cell in ws1['B:B']: #column B
    print('Printing from ' + str(cell.column) + str(cell.row))
    ws2.cell(row = cell.row, column = 1, value = cell.value)

wb.save('workbook1.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