Python: How to read the complete Excel file using XLRD

Hello Friends,

Greetings for the day

In previous article Python – Reading an Excel file using xlrd we have discussed about how to read the single cell of Excel file in Python using xlrd.

In today’s article we are going to discuss about how to read complete Excel file in Python using xlrd, but before we will discuss little bit of for loop.

What is for loop?

A for loop in Python is a control flow statement that is used to repeatedly execute a group of statements as long as the condition is satisfied.

Following is the Excel file sample which we will read in our program.

 Excel file
Fig – 1 Excel file snap which we are going to read in our program

Program to read the complete Excel file

  • Import the module – xlrd
import xlrd

  • We have to give the location of the file where our file is stored
location = "D:\Python programs\Excelfiletest.xls"

  • Open our excel workbook using xlrd.open_workbook()
workbook = xlrd.open_workbook(location)

  • Once we have the workbook object we can read the any sheet using workbook.sheet _by_index()
  • workbook.sheet _by_index() – takes the parameter sheet index, here we are reading first sheet from the workbook
sheet = workbook.sheet_by_index(0)

  • The above code will return sheet object
  • Now to print the complete Excel file we will use two for loop in the program
  • First we will make the to variable for rows and columns – iRowCounter and iColCounter
  • For loop for rows iRowCounter
for iRowCounter in range(sheet.nrows):

  • For loop for columns iColCounter
 for iColCounter in range(sheet.ncols):

  • We will fetch each cell value using – sheet.cell_value()
  • Then we will print the cell value for iRowCounter and iColCounter
print(sheet.cell_value(iRowCounter , iColCounter))

Complete program :

import xlrd

location = "D:\Python programs\Excelfiletest.xls"

workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(0)

for iRowCounter in range(sheet.nrows):

    for iColCounter in range(sheet.ncols):
       
        print(sheet.cell_value(iRowCounter , iColCounter))

 Python program to read xls file
Fig 2 – Python program to read xls file

Thank you for reading this article

We have very good series of Python articles, please have a look – https://knowledge-junction.in/category/python/

Have a nice day 🙂

You may also like...

1 Response

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: