How To Move Cell Ranges Using OpenPyXL?

Method

Move a range using the `move_range` method of the worksheet object:

ws.move_range(cr,rows,cols)

The first parameter of this method specifies the range to be moved, which must be a CellRange object; the rows parameter defines the vertical movement. If the value is greater than 0, it moves down; if the value is less than 0, it moves up. The cols parameter defines the horizontal movement. If the value is greater than 0, it moves to the right; if the value is less than 0, it moves to the left.

Sample Code

#Move the Cell Range

#Import load_workbook function
from openpyxl import Workbook

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

#Move the cell range
#Row: >0 moves down; <0 moves up
#Column: >0 moves right; <0 moves left

from openpyxl.styles import PatternFill
ws['D4'].fill=PatternFill(fill_type='solid', start_color='00FF00')
ws['F10'].fill=PatternFill(fill_type='solid', start_color='00FF00')
ws.move_range('D4:F10', rows=-1, cols=2)

wb.save('test.xlsx')
wb.close()
Move Cell Ranges Using OpenPyXL

Leave a Reply

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