iter_rows()
.iter_rows()
is a method provided by the openpyxl library in Python that allows you to iterate over a range of cells in a worksheet. The iter_rows()
method takes parameters specifying the starting and ending cells of the range and returns a generator that yields each row as a tuple of cell objects.
Iterating over rows in a worksheet is useful when processing or analyzing data in a specific range or subset of cells. For example, you may need to calculate the average value of a column or search for specific values or patterns in a set of cells.
Tarea
Swipe to start coding
- Store extracted data in a
json
file; "Product"
is at index1
;"Units"
sold is at index3
;"Manufacturing"
is at index4
.
Solución
import json
workbook = load_workbook(filename="sample_data.xlsx")
sheet = workbook.active
countries = {}
# Using the values_only because you want to return the cells' values
for row in sheet.iter_rows(min_row=2,
max_row=5,
min_col=2,
max_col=6,
values_only=True):
country_id = row[0]
country = {
"Product": row[1],
"Units Sold": row[3],
"Manufacturing": row[4]
}
countries[country_id] = country
# Using json here to be able to format the output for displaying later
print(json.dumps(countries))
Mark tasks as Completed
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 1. Capítulo 6
AVAILABLE TO ULTIMATE ONLY