Skip to main content

Writing an Excel File in Python

In our previous Python tutorial, you have learned how to Reading an Excel File in Python. In this tutorial, you will learn how to Write an Excel File in Python.

The Excel spreadsheet is a popular file type that lets to create, view, edit, and share your files with others quickly and easily.

In this tutorial, we will use Openpyxl module from Python to wrting to an Excel file with extension such as (xlsx/xlsm/xltx/xltm). The Openpyxl module allows to read and write Excel files.

So let’s proceed with coding:

Install Openpyxl Module

First we will install Openpyxl Python module to use for writing to an Excel file. We will use following command to install Openpyxl module.

pip install openpyxl

Write an Excel File

Now we will implement to write an Excel file using Openpyxl module. So first we will import Openpyxl module and create workbook object. Then we will get workbook active sheet object to write an Excel File.


import openpyxl

workBook = openpyxl.Workbook()
workSheet = workBook.active

We will provide the sheet title name.

workSheet.title = "Emp Data"

then we will set sheet coloumn name.

c1 = workSheet.cell(row = 1, column = 1)
c1.value = "Name"
c2 = workSheet.cell(row= 1 , column = 2)
c2.value = "Age"

Then we will insert data to the Excel sheet.

c3 = workSheet['A2']
c3.value = "William"
c4 = workSheet['B2']
c4.value = "35"

c5 = workSheet['A3']
c5.value = "Smith"
c6 = workSheet['B3']
c6.value = "40"

c7 = workSheet['A4']
c7.value = "Raina"
c8 = workSheet['B4']
c8.value = "50"

We will also add the sheets in the Workbook.

workBook.create_sheet(index = 1 , title = "new sheet")

Finally, we will save the workbook into Excel file.

workBook.save("emp_data.xlsx")

Output:

Complete Code To Write To An Excel File

Here is the complete to write an Excel file with data.

#write.py

import openpyxl

workBook = openpyxl.Workbook()
workSheet = workBook.active

workSheet.title = "Emp Data"

c1 = workSheet.cell(row = 1, column = 1)
c1.value = "Name"
c2 = workSheet.cell(row= 1 , column = 2)
c2.value = "Age"

c3 = workSheet['A2']
c3.value = "William"
c4 = workSheet['B2']
c4.value = "35"

c5 = workSheet['A3']
c5.value = "Smith"
c6 = workSheet['B3']
c6.value = "40"

c7 = workSheet['A4']
c7.value = "Raina"
c8 = workSheet['B4']
c8.value = "50"

workBook.create_sheet(index = 1 , title = "new sheet")

workBook.save("emp_data.xlsx")