使用 XLRD 模块在导入的 excel 文件中搜索字符串

Using XLRD module to search for a string on imported excel-file

我有一个 excel 文件,大约有 1000 行和 25 列宽。

我想做的是创建一个脚本,根据用户输入查看 excel 文件。 (本例中的名称)

我当前的代码如下:

import xlrd
file_location =r"C:\Users\extoskben\Desktop\Datorer.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
User = input("What's the users name?:   ")

我希望代码从 excel 文件中读取并根据匹配的名称打印所有列的结果。

编辑:

excel 文件的结构:

   [Name         ] [x] [x] [x] [Serialnumber] [x] [x] [   Model    ]
[1] Oskar Beneke    x   x   x   123456789      x   x  Thinkpad t470
[2] Example name    x   x   x   987654321      x   x  Thinkpad t470s

我想知道如何只打印第 1 行、第 5 行和第 8 行的结果,而不打印 "X's"。

这段代码可以满足您的需求:

import xlrd
file_location =r"C:\Users\extoskben\Desktop\Datorer.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
User = input("What's the users name?:   ")

for row in range(sheet.nrows):  # Iterate over every rows of the file
    if User == sheet.cell_value(row, 0):  # If the user name match the input
        for col in range(sheet.row_len(row)):  # Iterate over every columns of the cell
            print(str(sheet.cell_value(row, col)))  # Print the value of the cells.

编辑:

如果只想打印给定行的特定列(本例中的第一列、第五列和第八列),可以使用此版本的 for 循环:

columns_to_output = [0, 4, 7]  # List of columns to ouptput (starting with `0` for first column index)
for row in range(sheet.nrows):  # Iterate over every rows of the file
    if User == sheet.cell_value(row, 0):  # If the user name match the input
        for col in columns_to_output:  # Iterate over the column to output list
            print(str(sheet.cell_value(row, col)))  # Printing the cell at given column in the row.