使用 Python 和 Openpyxl 迭代不同列的行

Iterating Rows for Different Columns with Python and Openpyxl

我正在尝试使用 openpyxl 遍历 Excel 电子表格中的行。 我想要做的是检查当前行 A 列中的单元格是否为空,如果是,我需要在同一行上打印 B 列中的数据。 到目前为止,这是我的代码:

wb = openpyxl.load_workbook('worksheet.xlsx')
wb.active = 1 #Change the active sheet.
sheets = wb.sheetnames #The sheets.
currentSheet = wb[sheets[n]] #Chooses the current sheet from the workbook.

for row in currentSheet.iter_rows('A{}:A{}'.format(currentSheet.min_row, currentSheet.max_row)):
    for cell in row:
        if not cell.value:
            print(currentSheet['B''row'].value)

当我 运行 时,我得到以下输出:

  File "main.py", line 69, in get_callout
    print(currentSheet['B''row'].value)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\ope
pyxl\worksheet\worksheet.py", line 357, in __getitem__
    min_col, min_row, max_col, max_row = range_boundaries(key)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\ope
pyxl\utils\cell.py", line 135, in range_boundaries
    raise ValueError("{0} is not a valid coordinate or range")
ValueError: {0} is not a valid coordinate or range

如有任何帮助,我们将不胜感激!

编辑 我忘了说我也在使用 openpyxl 2.4.9,因为 2.5.3(当前版本)不允许我打开我需要使用的 Excel 工作簿。

这是您何时应该使用 Excel 表示法的示例。

for (a, b) in currentSheet.iter_rows(max_col=2):
   if a.value is None:
       print(b.value)

应该可以

我实际上想出了一个不同的方法!

这是我的代码,供将来可能偶然发现此问题的任何人使用:

    for r in range(1, currentSheet.max_row):
        cell = currentSheet.cell(row=r, column=12)
        if cell.value is None:
            data = currentSheet.cell(row=r, column=2)
            print(data.value)

基本上我所做的是检查 L (12) 列是否为空,如果是,我需要在同一行但在 B (2) 列中打印值。打印显然可以用其他任何东西改变(return 或其他东西)。