Iterate over all rows in a specific openpyxl column

I cannot figure out how to iterate through all the rows in the specified column using openpyxl.

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

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 
+13
source share
3 answers

You can specify the range to repeat using ws.iter_rows() :

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

Edit: for Charlie Clark, you can use ws.get_squared_range() alternately:

 # ... ws.get_squared_range(min_col=1, min_row=1, max_col=1, max_row=10) # ... 

Edit 2: for your comment, you want the cell values ​​in the 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 
+17
source

Why can't you just iterate over column "C" (version 2.4.7):

 for cell in ws['C']: print cell.value 
+13
source

You can also do this.

 for row in ws.iter_rows(): print(row[2].value) 

In doing so, you still iterate over the rows (but not the cells) and extract only the values ​​from column C in the row to print.

0
source

All Articles