In this tutorial, we will learn how to create a new worksheet in an Excel file using Python. This can help automate various data-related tasks, including reporting and tracking. We will be using the openpyxl package, which is a popular package designed specifically for interacting with Excel files using Python.
Step 1: Install openpyxl
Before you can create a new Excel worksheet using Python, you need to install the openpyxl package. To do this, simply run the following command:
1 |
pip install openpyxl |
Alternatively, you can also add openpyxl
to your requirements.txt
file if you’re using a virtual Python environment in your project.
Step 2: Import openpyxl
Once the package is installed, you need to import the module into your Python script. You can do this by adding the following line of code at the top of your Python file:
1 |
import openpyxl |
Step 3: Create a new Excel file
To create a new Excel file, simply create a new instance of the openpyxl.Workbook
class. The following line of code demonstrates how to do this:
1 |
wb = openpyxl.Workbook() |
After executing this line of code, you’ve now created a new Excel file in memory with a single default worksheet titled "Sheet"
.
Step 4: Create a new worksheet
To add a new worksheet to your Excel file, you can use the create_sheet()
method of the openpyxl.Workbook
instance. Here’s an example of how to create a new worksheet named “Data”:
1 |
ws = wb.create_sheet("Data") |
After running this line, your Excel file will now have a new worksheet titled "Data"
.
Step 5: Save the Excel file
After creating the new worksheet, you’ll need to save the Excel file to your computer’s filesystem. You can do this by using the save()
method of the openpyxl.Workbook
instance. Here’s an example of how to save your Excel file as “output.xlsx”:
1 |
wb.save("output.xlsx") |
At this point, your new Excel file with a new worksheet titled "Data"
should be saved as “output.xlsx” in your script’s working directory.
Full Code
1 2 3 4 5 6 7 8 9 10 |
import openpyxl # Step 1: Create a new Excel file wb = openpyxl.Workbook() # Step 2: Create a new worksheet ws = wb.create_sheet("Data") # Step 3: Save the Excel file wb.save("output.xlsx") |
Conclusion
In this tutorial, we’ve learned how to create and save a new Excel file with a new worksheet using Python and the openpyxl package. Following these steps can help automate data-related tasks, making the process more efficient and streamlined.