Count total number of rows and columns in a sheet using Openpyxl

In this tutorial, we will learn how to get or count the number of rows and columns of a sheet using openpyxl in Python.

Count the total number of rows and columns of the excel sheet in Python

To manage Excel files without using additional Microsoft application software, Python’s Openpyxl module is utilized. It is perhaps the greatest Python Excel module that enables you to automate Excel reports and conduct a variety of Excel functions. Using Openpyxl, you may carry out a variety of operations, including:-

  1. Analyzing data
  2. Recording data
  3. Edit Excel documents
  4. Creating charts and graphs
  5. Using numerous sheets
  6. such as sheet styling

You may install the Openpyxl module by installing it in your terminal with the help of the following command:

pip install openpyxl

Steps to Count the total number of rows and columns in a sheet using Openpyxl

The data of the excel file which we are using in this article,

Count total number of rows and columns in a sheet using Openpyxl

Step 1: Import Openpyxl’s load workbook function.

from openpyxl import load_workbook

Step 2: Give the Python program the way of the Succeed document you wish to open.

file = load_workbook('file.xlsx')

Step 3: Pick the principal dynamic sheet present in the exercise manual utilizing the file.active characteristic.

sheet = file.active

Step 4: Use the sheet.max_row and sheet.max_column properties in Openpyxl to obtain the maximum number of rows and columns from the Excel sheet in Python.

So our final code will be:

from openpyxl import load_workbook
file = load_workbook('file.xlsx')
sheet = file.active
print(f"Total number of row in the present sheet is {sheet.max_row}")
print(f"Total number of column in the present sheet is {sheet.max_column}")

The output will be:

Total number of row in the present sheet is 10
Total number of column in the present sheet is 23

Process finished with exit code 0

Also read: Change sheet name using openpyxl in Python

Leave a Reply

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