openpyxl 从 Excel 文件读取

openpyxl to read from Excel file

我有一些代码想用来遍历 excel 中的某些行,为此我打开了 pyxl。

我想为每一行打印如下内容:

'The product id is: ' + column 1 + 'and the product is: ' + column 2

但我不知道如何区分代码中的列。 我现在拥有的代码如下:

from openpyxl import load_workbook

file = load_workbook('path...file.xlsx')
list = file.active

for value in list.iter_rows(min_row=1, min_col=1, max_col=2, values_only=True):
    print(value)

我得到的结果如下:

('ProductID', 'Product')
('xxx', 'xxx')
...
('yyy', 'yyy')

所以我可以使用整行,但我不确定在打印时我应该如何引用行中的每个单元格。

有没有其他方法可以做到这一点?

您可以打开文件并使用 readlines() 然后遍历行并使用逗号分隔值以列出并用于例如value[0] 作为 id,value[1] 作为 product

请试试这个:

from openpyxl import load_workbook

file = load_workbook('path...file.xlsx')
sheet = file.active

for row in range(sheet.max_row):
    cell = sheet.cell(row=row, column=1)
    print(cell.value)