简体   繁体   中英

openpyxl to read from Excel file

I have some code which I want to use to iterate through some rows in excel, and for this i openpyxl.

I would like to, for each row, print something like this:

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

But I don't know how to distinguish between the columns in the code. The code I have right now is the following:

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)

And the result I get is the following:

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

So I can use the entire row, but I'm unsure as to how I should refer to each individual cell in the row when I print.

Is there a different way I should do this?

Please try this:

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)

you could do open file and use readlines() then iterate through the lines and use the comma separate the values in to list and use for eg value[0] as id and value[1] as product

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM