我有一个excel文件,大约有1000行25列宽。
我想做的是创建一个脚本,根据用户输入查看excel文件。(本例中为姓名(
我当前的代码如下:
import xlrd
file_location =r"C:UsersextoskbenDesktopDatorer.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"。
此代码可以执行您想要的操作:
import xlrd
file_location =r"C:UsersextoskbenDesktopDatorer.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.