Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any method to get the number of rows and columns present in .xlsx sheet using openpyxl?

Is there any method to get the number of rows and columns present in .xlsx sheet using openpyxl ? In xlrd,

     sheet.ncols 
     sheet.nrows

would give the column and row count. Is there any such method in openpyxl ?

like image 640
Kulkarni Sachin Avatar asked Feb 15 '16 11:02

Kulkarni Sachin


People also ask

How do I find the number of rows and columns in Openpyxl?

To find the max row and column number from your Excel sheet in Python, use sheet. max_row and sheet. max_column attributes in Openpyxl. Note - If you update a cell with a value, the sheet.

How do I get row count in Openpyxl?

After this we should import openpyxl in our code and then we should be ready to interact with excel. To get the count of the occupied rows in a worksheet, first of all we need to load the entire workbook by specifying the path where it is located. This is achieved with load_workbook() method.

How do I count rows in Excel using Python?

You can use len(df. index) to find the number of rows in pandas DataFrame, df. index returns RangeIndex(start=0, stop=8, step=1) and use it on len() to get the count.


2 Answers

Given a variable sheet, determining the number of rows and columns can be done in one of the following ways:

Version ~= 3.0.5 Syntax

rows = sheet.max_rows
columns = sheet.max_column

Version 1.x.x Syntax

rows = sheet.nrows
columns = sheet.ncols

Version 0.x.x Syntax

rows = sheet.max_row
columns = sheet.max_column
like image 195
Alexander Craggs Avatar answered Oct 10 '22 12:10

Alexander Craggs


A solution using Pandas to get all sheets row and column counts. It uses df.shape to get the counts.

import pandas as pd
xl = pd.ExcelFile('file.xlsx')
sheetnames = xl.sheet_names  # get sheetnames
for sheet in sheetnames:
    df = xl.parse(sheet)
    dimensions = df.shape
    print('sheetname', ' --> ', sheet)
    print(f'row count on "{sheet}" is {dimensions[0]}')
    print(f'column count on "{sheet}" is {dimensions[1]}')
    print('-----------------------------')
like image 25
Cam Avatar answered Oct 10 '22 13:10

Cam