Python: How to read the complete Excel file using XLRD
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.
Program to read the complete Excel file
- Import the module – 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))
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 🙂
[…] To get the solution check this link’s – part 1 – https://knowledge-junction.com/2021/08/22/python-how-to-read-the-complete-excel-file-using-xlrd/ […]
You must log in to post a comment.