In this tutorial, we will learn how to create a new sheet in Microsoft Excel using Python and the openpyxl library. The openpyxl library is a powerful tool that allows you to perform various operations on Excel files, such as reading, writing, and modifying data. Let’s dive in and explore how to create a new sheet using this versatile library.
Step 1: Install openpyxl
Before we begin, ensure that openpyxl is installed on your system. If you haven’t installed it yet, you can install it using pip:
1 |
pip install openpyxl |
Step 2: Import openpyxl modules
Import the required openpyxl modules that will enable you to work with Excel files:
1 |
from openpyxl import Workbook |
Step 3: Create a new Excel workbook
Create a new workbook using the Workbook() class:
1 |
wb = Workbook() |
This creates a new Excel workbook in memory with a default sheet named “Sheet”.
Step 4: Create a new sheet
To create a new sheet, call the create_sheet() method on the workbook object and pass the desired name of the sheet as an argument:
1 |
new_sheet = wb.create_sheet("New Sheet") |
This creates a new sheet named “New Sheet” in the workbook.
Step 5: Save the workbook to a file
Finally, save the workbook to a file by calling the save() method on the workbook object and passing the desired file name as an argument:
1 |
wb.save("Excel_Workbook.xlsx") |
This will save the workbook to a file named “Excel_Workbook.xlsx” in the current working directory.
Full Code
1 2 3 4 5 |
from openpyxl import Workbook wb = Workbook() new_sheet = wb.create_sheet("New Sheet") wb.save("Excel_Workbook.xlsx") |
Output
Excel_Workbook.xlsx (containing two sheets: "Sheet" and "New Sheet")
Conclusion
In this tutorial, we learned how to create a new sheet in an Excel workbook using Python and the openpyxl library. Following these steps will enable you to create new sheets in Excel files programmatically, allowing you to manipulate Excel data more efficiently and effectively.