Python Write Excel File using xlwt

Python Python Excel Python File xlwt

In this tutorial we will learn how to use xlwt package to write Excel file in Python.

Install xlwt package

Firstly you need to install xlwt package by command below.

pip install xlwt

Create Workbook and Sheet

Import xlwt package

import xlwt

First step to write Excel file we need to create workbook and add a new sheet.

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("contacts")

Create cell style

Below example code to create style for header cell with bold text and Arial font.

header_font = xlwt.Font()
header_font.name = 'Arial'
header_font.bold = True

header_style = xlwt.XFStyle()
header_style.font = header_font

Write cell data to Excel sheet

To write data to Excel cell we need to give the row and column of the cell as below.

sheet.write(0, 0, 'Name', header_style)
sheet.write(0, 1, 'Email', header_style)

sheet.write(1, 0, 'Julie Scott')
sheet.write(1, 1, 'julie@toricode.com')

sheet.write(2, 0, 'Harry Hernandez')
sheet.write(2, 1, 'harry@toricode.com')

Save to file

workbook.save('contacts.xls')

Complete Python code to write Excel file

import xlwt

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("contacts")

header_font = xlwt.Font()
header_font.name = 'Arial'
header_font.bold = True

header_style = xlwt.XFStyle()
header_style.font = header_font

sheet.write(0, 0, 'Name', header_style)
sheet.write(0, 1, 'Email', header_style)

sheet.write(1, 0, 'Julie Scott')
sheet.write(1, 1, 'julie@toricode.com')

sheet.write(2, 0, 'Harry Hernandez')
sheet.write(2, 1, 'harry@toricode.com')

workbook.save('contacts.xls')

Execute above Python code we will get the Excel file contacts.xls as below.

Python Write Excel File using xlwt