How To Create and Delete Worksheets Using OpenPyXL?

Method

To create a new worksheet, use the `create_sheet` method of the workbook object. Its syntax is:

ws=wb.create_sheet(title=None, index=None)

Where `title` is a string representing the name of the new worksheet, and `index` is an integer representing the position at which to insert the worksheet. Both parameters are optional. The method returns a worksheet object, which automatically becomes the active worksheet.

Common attributes:

  • active_cell
  • selected_cell
  • rows
  • columns
  • dimensions
  • max_column    #the highest column with data, 1-based index
  • max_row
  • min_column
  • min_row
  • merged_cell_ranges
  • show_gridlines
  • title
  • Values

To delete a specific worksheet, use the `remove` method of the workbook object. For example, to delete the `ws1` worksheet:

wb.remove(ws1)

Sample Code

#Create and Delete Worksheets

#Import load_workbook function
from openpyxl import load_workbook

#Load the workbook
wb=load_workbook(filename='wb2.xlsx')
#Get the active worksheet
ws=wb.active
#Output the title of the active worksheet
print(ws.title)

#Create a new worksheet with the default name
ws1=wb.create_sheet()
#Create a new worksheet named `Mysheet2`
ws2=wb.create_sheet('Mysheet2')
#Create a new worksheet named `Mysheet3`,
#placing it at the front
ws3=wb.create_sheet('Mysheet3', 0)
#Create a new worksheet named `Mysheet4`,
#placing it second to last
ws4=wb.create_sheet('Mysheet4', -1)

#Delete worksheet `ws4`
wb.remove(ws4)
#Delete worksheet `ws3`
del wb[ws3.title]

#Save the workbook
wb.save('test.xlsx')

#Close the workbook
wb.close()

Leave a Reply

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