Write to an excel file using openpyxl module in Python

This post will help you to write to an excel file using openpyxl module in Python. In first we have to know about the openpyxl module.

openpyxl

  • openpyxl: used for reading and writing Excel files.
  •  Without opening the application, we can take control of excel with the help of the openpyxl library.

Some of the important tasks can be done by openpyxl are,

  •  Read data from excel file
  • Write data to the excel file
  • Draw charts
  • Accessing excel sheets
  • Renaming sheets
  • Formatting
  • Sheet styling.

Program

  • At first, we have imported the openpyxl module. Then we imported the Workbook class from the openpyxl module. A Workbook is a container for all other parts of the document. We created a new workbook. A workbook is always created with at least one worksheet.
  • We can get it using Workbook.active property.
  • After that, we got a reference to the active sheet.
  • Then we can add values by mentioning the row and column. We can also mention cells where to insert values.
  •  Finally, we can save the excel file using the save() method.
  • Syntax: workbook.save(filename)

Let’s take a look at the program.

import openpyxl
from openpyxl import Workbook
wbook = openpyxl.Workbook() 
sheet = wbook.active 
cell1 = sheet.cell(row = 1, column = 1) 
cell1.value = "ANNIE"
cell2 = sheet.cell(row= 1 , column = 2) 
cell2.value = "RAJ"
cell3 = sheet.cell(row= 1 , column = 3) 
cell3.value = "JOHN"
cell4 = sheet.cell(row= 1 , column = 4) 
cell4.value = "JONATHAN"
cell5 = sheet['A2'] 
cell5.value = "RAM"
cell6 = sheet['B2'] 
cell6.value = "SHREYAS" 
cell7 = sheet['C2'] 
cell7.value = "PANT" 
cell8 = sheet['D2'] 
cell8.value = "HARDIK" 
wbook.save("example.xlsx") 

After performing the above operations, the excel file will look like below.

Excel Sheet

I hope that you learned something new from this post.

Leave a Reply

Your email address will not be published. Required fields are marked *