Methods:
- Given the coordinates of the top-left and bottom-right corners of a range, use these coordinates to reference the cell range. – A tuple of cell objects.
- Reference rows and columns – A tuple of cell objects.
- Use the `CellRange` class.
OpenPyXL code 1:
#Referencing Cell Ranges
#Import load_workbook function
from openpyxl import Workbook
#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active
#Get a range of cells
cr=ws['A1:C4']
#Or
#cr=ws['A1':'C4']
print(cr)
print(cr[2][2].value)
wb.save('test.xlsx')
wb.close()
OpenPyXL code 2:
#Referencing Cell Ranges
#Import load_workbook function
from openpyxl import Workbook
#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active
#Use the `CellRange` method to create a cell range object
from openpyxl.worksheet import cell_range as cr
cr0=cr.CellRange(min_row=2,max_row=5,min_col=3,max_col=6)
#Coordinates of cells in the bottom row of the range
print(cr0.bottom)
#Coordinates of cells in the top row of the range
print(cr0.top)
#Coordinates of cells in the leftmost column of the range
print(cr0.left)
#Coordinates of cells in the rightmost column of the range
print(cr0.right)
#Minimum row number in the range
print(cr0.min_row)
#Minimum column number in the range
print(cr0.min_col)
#Maximum row number in the range
print(cr0.max_row)
#Maximum column number in the range
print(cr0.max_col)
#Size of the range
print(cr0.size)
#Coordinates of the top-left and
#bottom-right cells of the range
print(cr0.bounds)
#Coordinates of the top-left and
#bottom-right cells of the range
print(cr0.coord)
#Coordinates of each row's cells in the range
for cell in cr0.rows:
print(cell)
#Coordinates of each column's cells in the range
for cell in cr0.cols:
print(cell)
#Coordinates of each individual cell in the range
for cell in cr0.cells:
print(cell)
wb.save('test.xlsx')
wb.close()