在openpyxl中迭代特定列中的所有行

61

我无法想出如何使用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

“ws”是什么?你是如何使用“openpyxl”的?请提供更多关于你试图实现的目标的细节,否则每个答案都将基于假设。 - danielhadar
1
@danielhadar 我认为ws是work_sheet的缩写。 - Smiles
8个回答

77

为什么不能只迭代列'C'呢?(版本2.4.7):

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

53
你可以使用ws.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

编辑:根据您的评论,您想要将单元格值放入列表中:

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 

2
ws.iter_rows() 的字符串参数是否仍然有效?我需要使用 ws.iter_rows(min_row=ws.min_row, max_row=ws.max_row) - xtian
1
使用Python3,我需要使用for row in ws.iter_rows(ws.min_row,ws.max_row)或者for row in ws来使其工作。 - Larry Guo
这整个“A1:A123”风格的业务似乎不再有效,可以像其他人建议的那样做,或者查看当前实现的定义:def iter_rows(self, min_row=None, max_row=None, min_col=None, max_col=None, values_only=False): - undefined

12

你也可以这样做。

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

通过这种方式,您仍在遍历行(但不是单元格),并仅从行中的列C中获取值以进行打印。


7

以上一些解决方案不太有效(可能是因为“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

打印所有指定列(例如从“E”到“L”的列)的行:

# 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

请记住以下几点:
  • sheet[N] 提供第 N 行的 'Cell' 对象列表。 (N 是从 1 开始的数字)
  • 要获取一行中的第一个列单元格,请使用 sheet[N][0]。(因为 sheet[N] 是一个 'tuple', 可以从 0 开始索引)。

2

可以这样说:

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)

我认为这个答案对我最有用。解释得很好。你还可以使用 ws.min_rowws.max_row 的组合来扫描所有已使用的行(即不是整个工作表),并在迭代器中保持第三列固定(即 C),例如: ws.iter_rows(min_row=ws.min_row, max_row=ws.max_row, min_col=3, max_col=3) - Domenico Spidy Tamburro

1

您可以使用单元格对象中的坐标属性。

坐标属性包含单元格地址的字符串格式。

例如,

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


1
我是这样做的。我不确定自己在做什么,但它确实避免了没有值的单元格。
from openpyxl import load_workbook
wb = load_workbook(filename = 'exelfile.xlsx')
ws = wb['sheet1']

for col in ws['A']:
    print (col.value)

-1
listaClientes =[]
    for row in datos.iter_rows(min_row=2, min_col=3, max_col=3):
        for cell in row:
            listaClientes.append(cell.value)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接