How To Traverse Rows/Columns Using OpenPyXL?

Method

Use the `rows` property to iterate over all rows with data, and `columns` to iterate over all columns with data. The `values` property provides access to the data in the sheet’s cell range.

Sample Code

#Iterating through Rows and Columns

#Import load_workbook function
from openpyxl import Workbook

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

#Iterate through each cell in the first row
for cell in ws['1']:
    print(cell.value)    #Output the value of each cell

#Iterate through each cell in the first column
for cell in ws['A']:
    print(cell.value)    #Output the value of each cell

#Iterate through the first to third rows
for row in ws['1:3']:
    for cell in row:      #Iterate through each row's cells
        print(cell.value)    #Output the value of each cell

#Iterate through the first to third columns
for column in ws['A:C']:
    for cell in column:   #Iterate through each column's cells
        print(cell.value)    #Output the value of each cell

#Iterate through all rows using the rows attribute of the worksheet
for row in ws.rows:
    line=[cell.value for cell in row]
    print (line)

#Iterate through all columns using the columns attribute of the worksheet
for column in ws.columns:
    line = [cell.value for cell in column]
    print (line)

#Use the values attribute to return data from each row, returned as a list
for row in ws.values:
    print(row)

#Output as a list
for row in ws.values:
    print(list(row))

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

Leave a Reply

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