遍历特定列openpyxl中的所有行 [英] iterate through all rows in specific column openpyxl

查看:1318
本文介绍了遍历特定列openpyxl中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何使用openpyxl遍历指定列中的所有行.

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

我要打印"C"列中所有行的所有单元格值

I want to print all of the cell values for all rows in column "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

推荐答案

您可以指定要使用

You can specify a range to iterate over with 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

根据查理·克拉克,您可以选择使用ws.get_squared_range():

per Charlie Clark you can alternately use ws.get_squared_range():

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

根据您的评论,您希望列表中的单元格值为:

Edit 2: 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 

这篇关于遍历特定列openpyxl中的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆