我正在编写一个程序,在工作表的第一行搜索特定的值(“文件名”)。一旦找到,它将遍历该列并返回其下的值(第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()
实际上,您在这里迭代的是行和单元格,而不是列和名称:
如果这样重写,可以看到得到一个单元格,如下所示:
所以你有一个手机。您需要获取列,您可以使用返回列索引的
cell.column
来执行此操作不过,与仅迭代第一行(最小行和最大行设置为1的iter_行)相比,更好的方法是只使用为此构建的
iter_cols
。因此:相关问题 更多 >
编程相关推荐