How To Reference a Cell Using OpenPyXL?

Method

A cell reference refers to finding the cell you want to operate on in a worksheet.

  • Use square brackets

ws[‘A1’]=0

  • Use the `cell` method of the worksheet object to reference and assign values
  • Use the `Cell` class

from openpyxl.cell.cell import Cell, MergedCell, WriteOnlyCell

from openpyxl.cell.read_only import ReadOnlyCell

 

Common Attributes

  • alignment
  • Border
  • col_idx
  • column
  • column_letter
  • comment
  • coordinate
  • data_type
  • encoding
  • fill
  • font
  • has_style
  • hyperlink
  • is_date
  • number_format
  • parent
  • row
  • value

Sample Code

#Referencing Cells

#Import load_workbook function
from openpyxl import Workbook

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

#Assign a value to cell A1
ws['A1']=123
#Assign a value to cell B2
ws['B2']='你好'
#Get the value from cell A1
cl=ws['A1']

#Return the Cell object
cl=ws.cell(row=4, column=2, value=10)

#Import the cell class
from openpyxl.cell import cell
#Use the Cell method to create a cell
cl=cell.Cell(worksheet=ws, row=4, column=2, value=10)

cl=ws['C3']    #Referencing a cell
print(cl.row)    #Row number of the cell
print(cl.column)    #Column number of the cell
print(cl.value)    #Value of the cell
print(cl.coordinate)    #Coordinates of the cell
print(cl.data_type)    #Data type of the cell value
cl.hyperlink='https:\\www.baidu.com'    #Link in the cell
print(cl.hyperlink)
#Offset to a cell at a specified position
#(e.g., 1 row down, 2 columns right)
h=cl.offset(row=1, column=2)
print(h.value)

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

Leave a Reply

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