How To Copy Cell Ranges Using OpenPyXL?

Method

Copying content:

from openpyxl.worksheet.cell_range import CellRange

cr=CellRange(‘D5:F7’)

cr2=CellRange(‘D12:F14’)

r=cr2.max_row-cr.max_row

c=cr2.max_col-cr.max_col

for cl in cr.cells:

      cl2=ws.cell(row=cl[0],column=cl[1])

      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)

Sample Code

#Copy Cell Ranges

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Import CellRange class
from openpyxl.worksheet.cell_range import CellRange

#Create a cell range object
cr=CellRange('D5:F7')
cr2=CellRange('D12:F14')

#Copy the values
r=cr2.max_row-cr.max_row
c=cr2.max_col-cr.max_col
for cl in cr.cells:
      cl2=ws.cell(row=cl[0],column=cl[1])
      ws.cell(row=cl[0]+r,column=cl[1]+c,value=cl2.value)

wb.save('test.xlsx')
wb.close()

Leave a Reply

Your email address will not be published. Required fields are marked *