openpyxl 模块没有打印输出

No print output from openpyxl modules

我是编码新手 - 正在尝试将其理解为处理实际代码。

我想浏览第一行中的所有列标题,找到显示 "Status" 的列标题并获取它的列字母。 据说之后我将遍历电子表格中的所有行并创建一个新文件,其中的行在 "Status" 列中只有某个关键字。 我的弗兰肯斯坦没有给我任何错误,但我无法获得列字母的打印输出。 temp_value 创建变量的目的是保存该列字母并在代码后面的某些 loops/calculations 中使用它。

感谢您抽出宝贵时间,希望您能帮帮我。 P.S。我积极浏览 openpyxl 官方指南,但运气不佳。我认为我的主要问题是无法规划我的代码结构 - 对任何想法持开放态度并在此处提出建议:)

    import openpyxl
    from openpyxl import Workbook
    from openpyxl.utils import get_column_letter

    wb = openpyxl.load_workbook("myfile.xlsx")
    sheet = wb.active
    temp_data = str()

    #TODO: Find "Status" column to sift through only what we need later

    print("Reading through column titles...")

    for column in range (1, 10):
        column_letter = get_column_letter(column)
        if sheet[column_letter+str(column)].value == "Status":
            temp_data = column_letter

    print(temp_data)

在您的描述中,您说的是循环遍历 第一行 的列标题。代码“sheet[column_letter+str(column)].value 将生成 A1,B2,C3...

import openpyxl
from openpyxl import Workbook
from openpyxl.utils import get_column_letter

wb = openpyxl.load_workbook("myfile.xlsx")
sheet = wb.active
temp_data = str()

# TODO: Find "Status" column to sift through only what we need later

print("Reading through column titles...")

for column in range(1, 10):
    column_letter = get_column_letter(column)
    if sheet[column_letter + '1'].value == "Status":
        temp_data = column_letter

print(temp_data)

您实际上很少会在自己的代码中需要 get_column_letter

for cell in ws[1]:
   if cell.value == "Status":
       print(cell.column_letter)