Sunday, May 24, 2026

Python Material - Part - 31 - xlwt_Module

 __author__ = "Narendra Boyina"

# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> How to install xlwt module
--> purpose xlwt with example

"""

import sys, calendar, datetime,random,string,math

import xlwt
from xlwt import Workbook
import xlrd
from xlrd import open_workbook
import time
from datetime import date



def write_data_to_excel():
# book = xlwt.Workbook(encoding="utf-8")
book = Workbook() # creating work book & it's instance

swetha_sheet = book.add_sheet("swetha")
rajesh_sheet = book.add_sheet("Rajeesh")
sheet3 = book.add_sheet("Durga")
meera_sheet = book.add_sheet("Meera")
sheet5 = book.add_sheet("jasmin")
meera_sheet.write(0, 0, "Meera")
swetha_sheet.write(1,1,"I am swetha")
rajesh_sheet.write(0,4,"Hi")

# titles = ["Tag Name", "parameter_name", "state", "results"]
# for i, j in enumerate(titles):
# swetha_sheet.write(3, i, j) # row, colum, value
# meera_sheet.write(2, i, j)
# fmt_1 = xlwt.Style.easyxf("""
# font: name Arial;
# borders: left thick, right thick, top thick, bottom thick;
# pattern: pattern solid, fore_colour blue;
# """)
# for i, j in enumerate(titles):
# rajesh_sheet.write(1, i, j,fmt_1) # row, colum, value

date_1 = date(2024, 8, 16)
current_time = time.ctime() # it will print time stamp

fmt_2 = xlwt.Style.easyxf("""
font: name Arial;
borders: left thick, right thick, top thick, bottom thick;
pattern: pattern solid, fore_colour yellow;
""", num_format_str='YYYY-MM-DD')
meera_sheet.write(6, 1, date_1)
# meera_sheet.write(8, 8, current_time, fmt_2)

book.save("Narendra.xls")


write_data_to_excel()

""" reading data from Excel workbook"""



def read_data_from_excel_file(path):
"""
Open and read an Excel file
"""
# book = xlrd.open_workbook(path)
book = open_workbook(path) # creating object for workbook (by using that object, can perform required operations)

print(book.nsheets) # print number of sheets
print(book.sheet_names()) # print sheet names

# get the first worksheet based on index
# swetha_sheet = book.sheet_by_index(0)
swetha_sheet = book.sheet_by_name("swetha")
print(swetha_sheet.row_values(1)) # can get the row based values
print(swetha_sheet.col_values(0)) # can get the colum based values

# read a cell
Meera_sheet = book.sheet_by_index(3)
value = Meera_sheet.cell_value(2,2)
print(value)


if __name__ == "__main__":
path = r"/Class_38_xlwt_module\Narendra.xls"
read_data_from_excel_file(path)

Author: Boyina Narendra

Supporting Author: M. Meera Sindhu

Request: If you find this information useful, please provide your valuable comments

No comments:

Post a Comment