How To Copy and Move Worksheets Using OpenPyXL?

Method

To copy a worksheet, use the `copy_worksheet` method:

>>> copy_sheet=wb.copy_worksheet(ws)

To move a worksheet (cut and paste), use the `move_sheet` method:

>>> wb.move_sheet(ws, offset=1)

The `offset` parameter specifies the number of positions to move the worksheet. If the value is greater than 0, the source sheet moves to the right by the specified number; if it’s less than 0, it moves to the left.

Sample Code

#Copying and Moving Worksheets

#Import load_workbook function
from openpyxl import Workbook

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

#Copy worksheets
copy_sheet1=wb.copy_worksheet(ws)
copy_sheet2=wb.copy_worksheet(ws)
#Specify the title of the first copied worksheet
copy_sheet1.title='NewSheet'

#Move worksheets
#If the offset value n > 0, move n columns to the right;
#n < 0, move n columns to the left
wb.move_sheet(ws, offset=1)

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

Leave a Reply

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