How to Get Total Columns and Rows in an Excel Sheet by openpyxl

Python openpyxl library has two functions that can be used to get the number of rows and columns in the specified Excel sheet.

Getting the total number of rows and columns in Excel by openpyxl

Python openpyxl library has two functions that can be used to get the number of rows and columns in the specified Excel sheet.

These functions are:

  • max_row
  • max_column

See the example below for using each of these functions.

An example of max_row function to get row count

For our examples, we are using the following sample sheet:

Excel-Rows-Cols-Total

You can see, it’s a Product Information sheet that contains a few columns and rows. First, let us get the number of rows by using openpyxl:

The code:

Result:

Total Number of Rows in Product Information Sheet =  11

Compare it with the sheet above and you can see we have total of 11 rows including the header row.

Getting total number of columns in the sheet

Now let us have a look at getting the total count of columns in our Product information sheet.

The code:

Result:

What if rows are empty?

So, what max_row function returns if certain rows are empty in the sheet? Have a look at the sample sheet below where we deleted four rows of data:

Excel-Find-Row-emprty

While running the same code as in the first example, see what we get the output:

The code:

Result:

So, we get the same result i.e. 11 because the maximum row index of the file is eleven.

What about if you want to get the result without empty rows?

The Solution

The following simple solution can be used for getting the total data rows only. We have a small function that gets the data rows only.

In the Python program below, we will display both – including empty rows and excluding empty rows. Have a look:

Python program:

Result: