简体   繁体   中英

Trying to copy a range of cells from one workbook to another using OPENPYXL

i am fairly new to Python and am trying to copy a selected range of cells (for instance A4:A66) from one Workbook to another. I have managed to take the range i need but am having trouble copying it into another workbook. The code is as follows:

import openpyxl as xl;

#Open source workbook
filename = r'C:\Users\FileDestination\SOURCE.xlsx'
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]

#Open destination workbook
filename1 = r'C:\Users\FileDestination\Destination.xlsx'
wb2 = xl.load_workbook(filename1)
ws2 = wb2.active

#Read the maximum number of columns and rows in source
mr = ws1.max_row
mc = ws1.max_column

#Copying source range values from source to destination
for r in ws1['B16':'B31']:
    for c in r:
        print(c.value) #Just to see the range selected
        ws2.cell(row = 1, column = 1).value = c.value #I don't believe this is correct as it doesn't work

wb2.save(str(filename1)) #Saving the new workbook

print("Range successfully copied to new Workbook")

The last part of this code is what is perplexing me... I am unsure how i should copy the range, the above code just copies the last line in the range in the first row&column on new Workbook. Also, i know it is pulling the range i want, just not sure how to copy.

Any help would be much appreciated, and thank you

See this

x = 1
#Copying source range values from source to destination
for r in ws1['B16':'B31']:
    for c in r:
        print(c.value) #Just to see the range selected
        ws2.cell(row = x, column = 1).value = c.value
        x += 1

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