Count number of rows and columns in an excel file in Python

Who doesn’t know about Excel Files these days? Whether you tabulate the score of an exam of a class in schools or you make a bill and store information of a payment you have or analyzing the data for a particular area; Excel Files are a one-step solution for making these.

Well, in the programming world also, excel used for a number of purposes. For example, datasets for machine learning can be in the form of excel files. In Python, we can work with excel in many ways.

Python program to count the no of Rows & Columns of an excel file

In this article, I’m here to show how to count the number of rows and columns from an excel file with the help of Python. Before programming in Python, I must recommend installing xlrd package in Python as this library is used for reading & formatting data from excel files having extensions .xls or .xlsx.

Also, read:

Just follow the steps given below:

Install xlrd package

To install xlrd using Windows, open Command Prompt and type the command given below:

python -m pip install -U xlrd

or if you’re using¬†Linux or Raspberry Pi¬†then type the command on your respective terminals:

sudo pip install xlrd

Creating an Excel File

Now we create an excel file from Microsoft Excel consisting of rows and columns given below:

Excel file

Write our Python Program

After creating the file, here the main part comes: we write the following code. For a better understanding of the code, I used comment lines to clarify the steps.

import xlrd as xl                             #Import xlrd package

loc = ("Filelocation\filename.xlsx")          #Giving the location of the file 
  
wb = xl.open_workbook(loc)                    #opening & reading the excel file
s1 = wb.sheet_by_index(0)                     #extracting the worksheet
s1.cell_value(0,0)                            #initializing cell from the excel file mentioned through the cell position
  
print("No. of rows:", s1.nrows)               #Counting & Printing thenumber of rows & columns respectively
print("No. of columns:", s1.ncols) 

Output:

No. of rows: 6
No. of columns: 4

Just follow the comment lines in our code to understand each and every step.

 

Leave a Reply

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