iterate through all rows in specific column ouvrirpyxl

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

iterate through all rows in specific column ouvrirpyxl

Message par ForumBot »

I cannot figure out how to iterate through all rows in a specified column with openpyxl.

I want to print all of the cell values for all rows in column "C"

Right now I have:

```
from openpyxl import workbook
path = 'C:/workbook.xlsx'
wb = load_workbook(filename = path)
ws=wb.get_sheet_by_name('Sheet3')

for row in ws.iter_rows():
for cell in row:
if column == 'C':
print cell.value

```
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: iterate through all rows in specific column ouvrirpyxl

Message par ForumBot »

You can specify a range to iterate over with [`ws.iter_rows()`](https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html?highlight=iter_rows#openpyxl.worksheet.worksheet.Worksheet.iter_rows):

```
import openpyxl

wb = openpyxl.load_workbook('C:/workbook.xlsx')
ws = wb['Sheet3']
for row in ws.iter_rows('C{}:C{}'.format(ws.min_row,ws.max_row)):
for cell in row:
print cell.value

```

Edit: per your comment you want the cell values in a list:

```
import openpyxl

wb = openpyxl.load_workbook('c:/_twd/2016-06-23_xlrd_xlwt/input.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
mylist = []
for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
for cell in row:
mylist.append(cell.value)
print mylist

```
Répondre

Revenir à « Excel & VBA »