如何使用python 3在xlsx文件中搜索数据?

时间:2021-08-18 13:59:03

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.

我正在尝试搜索用户名 - 在xlsx-'saito'中(我手动将其添加到xslx)并且大多数在线答案仅在您搜索特定单元格时才起作用。我的目的是创建一个登录程序,我可以在其中搜索用户名,如果文件中存在用户名然后询问相关密码,仍然无法找到如何搜索字符串。

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.

Accounts.xlsx是我将用于搜索用户名的文件。

1 个解决方案

#1


0  

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:

Openpyxl对于使用.xlsx文件非常有用。如果您只想检查用户名是否在文件中的任何位置,您可以提取所有值,如下所示:

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:

#1


0  

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:

Openpyxl对于使用.xlsx文件非常有用。如果您只想检查用户名是否在文件中的任何位置,您可以提取所有值,如下所示:

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: