Python Write Excel xlsx File with Multiple WorkSheet using OpenPyXL
In this Python openpyxl tutorial we learn how to write Excel xlsx files with multiple sheets using the openpyxl package.
How to install the openpyxl package
Firstly, Install the openpyxl package using the command below.
pip install openpyxl
Step by step to write Excel xlsx file with multiple worksheet
Import the Workbook from the openpyxl package.
from openpyxl import Workbook
Create a new Workbook object.
wb = Workbook()
By default, the Workbook created with a default Worksheet, In the following code we access the default active Worksheet and change its title.
sheet1 = wb.active
sheet1.title = 'Test Sheet 1'
We can create a new Worksheet using the create_sheet() method as below.
sheet2 = wb.create_sheet('Test Sheet 2')
sheet3 = wb.create_sheet('Test Sheet 3')
The create_sheet() method also allows you to create a new Worksheet and insert it to a specific position.
sheet3 = wb.create_sheet('Test First Sheet', 0)
Then save the Workbook as test.xlsx file.
wb.save('test.xlsx')
The complete Python program as below.
write_multiple_worksheet_excel.py
from openpyxl import Workbook
wb = Workbook()
sheet1 = wb.active
sheet1.title = 'Test Sheet 1'
sheet2 = wb.create_sheet('Test Sheet 2')
sheet3 = wb.create_sheet('Test Sheet 3')
sheet3 = wb.create_sheet('Test First Sheet', 0)
wb.save('test.xlsx')
Execute the above Python program we will get the Excel file test.xlsx as below screenshot.
Happy Coding 😊