我无法弄清楚如何使用openpyxl迭代指定列中的所有行。
我想打印“C”列
中所有行的所有单元格值现在我有:
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
答案 0 :(得分:20)
您可以使用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
编辑:根据Charlie Clark,您可以选择使用ws.get_squared_range()
:
# ...
ws.get_squared_range(min_col=1, min_row=1, max_col=1, max_row=10)
# ...
编辑2:根据您的评论,您需要列表中的单元格值:
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
答案 1 :(得分:18)
为什么不能迭代列'C'(版本2.4.7):
for cell in ws['C']:
print cell.value
答案 2 :(得分:1)
您也可以这样做。
for row in ws.iter_rows():
print(row[2].value)
使用此方法,您仍在遍历行(而不是单元格),仅从行中的C列中提取值以进行打印。
答案 3 :(得分:1)
上面的一些解决方案不能很好地工作(可能是由于'openpyxl'的最新版本)。在尝试了不同的方法之后,我使用了以下方法:
import openpyxl
sheet = openpyxl.load_workbook('myworkbook.xlsx')['Sheet1']
# Iterating through All rows with all columns...
for i in range(1, sheet.max_row+1):
row = [cell.value for cell in sheet[i]] # sheet[n] gives nth row (list of cells)
print(row) # list of cell values of this row
# For example we need column 'E' to column 'L'
start_col = 4 # 'E' column index
end_col = 11 # 'L' column index
for i in range(1, sheet.max_row+1):
row = [cell.value for cell in sheet[i][start_col:end_col+1]]
print(row) # list of cell values of this row
请记住以下几点:
答案 4 :(得分:1)
它可以是:
import openpyxl
path = 'C:/workbook.xlsx'
# since is a print, read_only is useful for making it faster.
wb = openpyxl.load_workbook(filename = path, read_only=True)
# by sheet name
ws=wb['Sheet3']
# non-Excel notation is col 'A' = 1, col 'B' = 2, col 'C' = 3.
# from row = 1 (openpyxl sheets starts at 1, not 0) to no max
for row in ws.iter_cols(min_row=1, min_col=3, max_col=3):
# for each row there is one cell object (since min_col = max_col)
for cell in row:
# so we print the value
print(f'C{row}: ', cell.value)
答案 5 :(得分:0)
我就是这样做的。我不确定我在做什么,但它确实避免了没有值的单元格。
from openpyxl import load_workbook
wb = load_workbook(filename = 'exelfile.xlsx')
ws = wb['sheet1']
for col in ws['A']:
print (col.value)
答案 6 :(得分:0)
您可以在单元格对象中使用坐标属性。
坐标属性包含字符串格式的单元格地址。
例如
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 'C' in cell.coordinate:
print cell.value
答案 7 :(得分:-2)
listaClientes =[]
for row in datos.iter_rows(min_row=2, min_col=3, max_col=3):
for cell in row:
listaClientes.append(cell.value)