openpyxl
  1. openpyxl-creating-and-deleting-worksheets

Creating and Deleting Worksheets - ( Working with Worksheets )

Heading h2

Syntax

# Creating a new worksheet
new_sheet = workbook.create_sheet(title="New Sheet")

# Deleting a worksheet
workbook.remove(worksheet)

Example

import openpyxl

# Load the workbook
workbook = openpyxl.load_workbook('example.xlsx')

# Create a new worksheet
new_sheet = workbook.create_sheet(title="New Sheet")
print(workbook.sheetnames)

# Delete a worksheet
sheet_to_delete = workbook['Sheet2']
work.remove(sheet_to_delete)
print(workbook.sheetnames)

# Save the changes to the workbook
workbook.save('example.xlsx')

Output

The output will be the names the worksheets in the workbook and after adding and deleting a worksheet.

['Sheet1', 'Sheet2', 'Sheet3', 'New Sheet']
['Sheet1', 'Sheet3', 'New Sheet']

ExplanationIn the context of working with Excel files in Python, worksheets refer to individual tabs or sheets within a workbook. Openpyxl is a Python library that allows us to create, read, and modify Excel files. We create and delete worksheets in an Excel file using Openpyxl.

In the code example above, we first load the existing workbook using openpyxl.load_workbook(). Then, we create a new worksheet using workbook.create_sheet() and provide a title for the worksheet. Next, we delete an existing worksheet using workbook.remove() and passing the worksheet object to deleted as an argument. Finally, we save the changes back to the Excel file using workbook.save().

Use

Creating and deleting worksheets in an Excel file is a common operation when working with spreadsheets. It allows us to organize data into separate sheets and makes it easier to analyze and manage large datasets.

Points

  • Worksheets in an Excel file refer to individual tabs or sheets within the workbook
  • Openpyxl is a Python library that allows us to create, read, and modify Excel files
  • workbook.create_sheet() is used to create a new worksheet and workbook.remove() is used to delete a worksheet After making changes to a workbook, we need to save the changes using workbook.save()

Summary

In conclusion, creating and deleting worksheets in an Excel file is a simple yet important operation that allows us to organize data into separate sheets. We can use Openxl, a Python library, to create and delete worksheets in an Excel file. We need to load the workbook, create or delete the worksheet, and then save the changes back to the workbook.

Published on: