Luis Alencastro
Luis Alencastro

Reputation: 3

How to search for data in an xlsx file using python 3?

I'm trying to search for a username -within a xlsx- 'saito' (I added this to the xslx manually) and most of the answers online work only when you search for a specific cell. My intention is to make a login program where I can search for a username and if the username exists in the file then ask for the related password after, still can't find out how to search for a string though.

Below is my current code...

counter = 0 
print('type L to log in or C to create an account')
decision = input().lower()
if decision == 'l':
    while counter == 0:
        print('please enter your user name')
        username = input()
        while username == '':
            print('please enter a valid username')
            username = input()
        if username in Accounts.xlsx:
            print('please enter your password')
            counter = counter + 1
        else:
            print('The username you have entered has not been recognised, please try again')
elif decision == 'c':
    print('I'll do the user creation later')
else:
    print('please log in or create a user')

Accounts.xlsx is the file I will be using to search for the usernames.

Upvotes: 0

Views: 3639

Answers (1)

MartinBorak
MartinBorak

Reputation: 26

Openpyxl is very useful for working with .xlsx files. If you just want to check whether a username is anywhere in the file, you can extract all of the values like so:

from openpyxl import load_workbook

wb = load_workbook(filename='Accounts.xlsx')
sheet = wb['sheet_name']

names = []

for i in range(1, sheet.max_row + 1):
    for j in range(sheet.max_column):
        if sheet[i][j].value:
            names.append(sheet[i][j].value)

Then just check whether a username is in the list

if username in names:

Upvotes: 1

Related Questions