简体   繁体   中英

Using openpyxl to find a value in a particular column and assign each value of the row to its own variable

I'm new to openpyxl so if there is an error I didn't notice it. I have tried that the program looks for a name in a column from an excel table and if the name is found, each value in the row should be assigned to a variable. The search for the name works, but I don't know how to assign the individual values to the variables. Below the code is an example.

Code:

import openpyxl

file = r"C:\Users\user\Documents\info.xlsx"
excel_file = openpyxl.load_workbook(file, read_only=True)
excel_sheet = excel_file["sheet2"]

user_input = input("Name: ")

for row in excel_sheet.rows:
    if user_input in row[0].value:
        for cell in row:
            print(cell.value)

Example:

https://i.stack.imgur.com/Wv8oU.png

name1 = Markus, age1 = 40, country1 = UK...

Is it not as simple as:

file = r"C:\Users\user\Documents\info.xlsx"
excel_file = openpyxl.load_workbook(file, read_only=True)
excel_sheet = excel_file["sheet2"]

user_input = input("Name: ")
name = None
age = None
country = None

for row in excel_sheet.rows:
    if user_input in row[0].value:
        name = row[0].value
        age = row[1].value
        country = row[2].value
        break

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