Python Write Excel xlsx File using OpenPyXL

In this Python openpyxl tutorial we learn how to write Excel xlsx files 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 simple Excel xlsx file

Import the Workbook from the openpyxl package.

from openpyxl import Workbook

Create a new Workbook object.

workbook = Workbook()

By default, the Workbook created with a default Worksheet, In the following code we access the default active Worksheet and change its title to Contacts.

worksheet = workbook.active
worksheet.title = 'Contacts'

We can access each cell in the Worksheet to assign values as below.

worksheet['A1'] = "First Name"
worksheet['B1'] = "Last Name"

worksheet['A2'] = "Harry"
worksheet['B2'] = "Hernandez"

worksheet['A3'] = "Julie"
worksheet['B3'] = "Scott"

Then save the Workbook as contacts.xlsx file.

workbook.save("contacts.xlsx")

The complete Python program as below.

write_excel_file.py

from openpyxl import Workbook

workbook = Workbook()

worksheet = workbook.active
worksheet.title = 'Contacts'

worksheet['A1'] = "First Name"
worksheet['B1'] = "Last Name"

worksheet['A2'] = "Harry"
worksheet['B2'] = "Hernandez"

worksheet['A3'] = "Julie"
worksheet['B3'] = "Scott"

workbook.save("contacts.xlsx")

Execute the above Python program we will get the Excel file contact.xlsx as below screenshot.

Python Write Excel xlsx File using openpyxl

Write Excel xlsx file with row and column index

We can also use the Worksheet.cell() method to write values to Excel cells using the row and column index number as below.

worksheet.cell(1, 1, "First Name")
worksheet.cell(1, 2, "Last Name")
worksheet.cell(1, 3, "Email")

worksheet.cell(2, 1, "Julie")
worksheet.cell(2, 2, "Scott")
worksheet.cell(2, 3, "julie@toricode.com")


worksheet.cell(3, 1, "Harry")
worksheet.cell(3, 2, "Hernandez")
worksheet.cell(3, 3, "harry@toricode.com")

The complete Python program as below.

write_excel_file_with_cell.py

from openpyxl import Workbook, workbook

workbook = Workbook()

worksheet = workbook.active
worksheet.title = 'Customers'

worksheet.cell(1, 1, "First Name")
worksheet.cell(1, 2, "Last Name")
worksheet.cell(1, 3, "Email")

worksheet.cell(2, 1, "Julie")
worksheet.cell(2, 2, "Scott")
worksheet.cell(2, 3, "julie@toricode.com")


worksheet.cell(3, 1, "Harry")
worksheet.cell(3, 2, "Hernandez")
worksheet.cell(3, 3, "harry@toricode.com")

workbook.save('customers.xlsx')

Execute the above Python program we will get the Excel file customers.xlsx as below screenshot.

Python Write Excel xlsx File using openpyxl

Happy Coding 😊