Openpyxl:如何获取特定列的值?

2024-10-03 19:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个程序,在工作表的第一行搜索特定的值(“文件名”)。一旦找到,它将遍历该列并返回其下的值(第2行到第x行)

我已经知道如何遍历工作表中的第一行,并获取包含特定值的单元格,但现在我需要遍历该列并打印出这些值。我该怎么做

import os
import sys
from openpyxl import load_workbook

def main():

    column_value = 'Filenames'

    wb = load_workbook('test.xlsx')
    script = wb["Script"]

# Find "Filenames"
for col in script.iter_rows(min_row=1, max_row=1):
    for name in col:
        if (name.value == column_value):
            print("Found it!")
            filenameColumn = name
            print(filenameColumn)
    
# Now that we have that column, iterate over the rows in that specific column to get the filenames
for row in filenameColumn: # THIS DOES NOT WORK
    print(row.value)

main()

Tags: nameinimportforthatvaluemainload
1条回答
网友
1楼 · 发布于 2024-10-03 19:30:03

实际上,您在这里迭代的是行和单元格,而不是列和名称:

for col in script.iter_rows(min_row=1, max_row=1):
    for name in col:

如果这样重写,可以看到得到一个单元格,如下所示:

for row in script.iter_rows(min_row=1, max_row=1):
    for cell in row:
        if (cell.value == column_value):
            print("Found it!")
            filenameCell = cell
            print(filenameCell)

所以你有一个手机。您需要获取列,您可以使用返回列索引的cell.column来执行此操作

不过,与仅迭代第一行(最小行和最大行设置为1的iter_行)相比,更好的方法是只使用为此构建的iter_cols。因此:

for col in script.iter_cols():
      # see if the value of the first cell matches
      if col[0].value == column_value:
         # this is the column we want, this col is an iterable of cells:
         for cell in col:
            # do something with the cell in this column here

相关问题 更多 >