1.导入需要的库

import xlrd----注意xlrd版本1.2.0
import re
import os

2.参数

参数详解
pathxlsx文件路径
sheet_index_number第几个sheet
row_name要查找的列名称

3.代码部分

# 找excel指定列返回所在sheet索引值   
def fond_excel_info(path,sheet_index_number,row_name):

    # 处理路径
    r = re.sub(r'\\\\', r'\\', path)
    
    # 后缀判断
    paths_file = r.split('.')[-1]
    file_path_xlsx = "xlsx"
    if paths_file != file_path_xlsx:
        print("待提取Excel文件后缀应为.xlsx",flush=True)
        os._exit(0)
    # 打开excel文件,创建一个workbook对象
    try:
        rbook = xlrd.open_workbook(r)      
    except:
        print("文件异常或路径有误,请检查!",flush=True)
        os._exit(0)
    rbook.sheets()
    # sheet_index_number-1由于索引是0开始
    read_sheet = rbook.sheet_by_index(sheet_index_number-1)
    # 获取会话记录所在索引
    index_number = -1 
    result_index = 0
    # 在第一个sheet找name列
    for row in read_sheet.get_rows():
        try:
            while row:
                index_number+=1
                price_column = row[index_number]
                price_value = price_column.value
                text_name = str(price_value) 
                if text_name == str(row_name):
                    result_index = index_number  # 字段索引
        except:
            pass       
    if result_index == 0:     
        print("没有找到此列",flush=True)
    return result_index
 
print(fond_excel_info(r'test.xlsx',1,'name'))

4.test.xlsx

image.png

索引为1
image.png


z
1 声望0 粉丝

所到之处,寸草不生