How To Used Cell Range of a Worksheet Using OpenPyXL?

Method

When the first N rows or columns of data are empty, there may be issues when iterating over all rows using the `rows` property of the worksheet object or over all columns using the `columns` property.

Use the following properties of the worksheet object to construct a `CellRange` object:

>>> from openpyxl.worksheet.cell_range import CellRange

>>> cr=CellRange(min_col=ws.min_column,max_col=ws.max_column,   min_row=ws.min_row,max_row=ws.max_row)

>>> cr.coord

Sample Code

#Used Range of Cells in a Worksheet

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Import the CellRange function
from openpyxl.worksheet.cell_range import CellRange

#Use the CellRange function to create a cell range object
cr=CellRange(min_col=ws.min_column,max_col=ws.max_column, \
             min_row=ws.min_row,max_row=ws.max_row)

#Output the coordinates of the cell range
print(cr.coord)

wb.save('test.xlsx')
wb.close()

Leave a Reply

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