How To Traverse Regions Using OpenPyXL?

Method

Use a nested `for` loop to iterate over the range A1:C3 and output the data in each cell.

>>> for row in ws[“A1:C3”]:   # Iterate through the rows in the range

            for cell in row:    # Iterate through each cell in the rows

                print(cell.value)

The following code saves the data from the specified range into the list `data` and outputs the data.

>>> data = []

>>> for row in ws[“A1:C3”]:

           rv = []

           for cell in row:

               rv.append(cell.value)

           data.append(rv)

>>> print(data)

The following properties provide the bounds of the data area in the worksheet:

  • min_row:the minimum row number of the data area
  • min_column:the minimum column number of the data area
  • max_row:the maximum row number of the data area
  • max_column:the maximum column number of the data area
  • The `iter_rows` and `iter_cols` methods allow for iterating through specific rows and columns within a given range.

Sample  Code

#Iterating Through Cell Ranges

#Import load_workbook function
from openpyxl import Workbook

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

#Iterate through the rows within a cell range
for row in ws['A1:C3']:
    #Iterate through the cells of each row within a cell range
    for cell in row:
        print(cell.value)    #Output the value of each cell

#Save the data from a specified range into a list called data
data = []
for row in ws["A1:C3"]:
    rv = []
    for cell in row:
        rv.append(cell.value)
        data.append(rv)
#Output the list
print(data)

#Get and output data using the range property
#provided by the worksheet object
wb=load_workbook('test.xlsx')
ws=wb.active
print([ws.min_row,ws.max_row,ws.min_column,ws.max_column])

for row in ws.iter_rows(min_row=3, max_col=4, max_row=5):
    line = [cell.value for cell in row]
    print (line)

for col in ws.iter_cols(min_row=3, max_col=4, max_row=5):
    line = [cell.value for cell in col]
    print (line)

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

Leave a Reply

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