关于python:python查找excel文件指定列返回所在索引值

3次阅读

共计 952 个字符,预计需要花费 3 分钟才能阅读完成。

1. 导入须要的库

import xlrd---- 留神 xlrd 版本 1.2.0
import re
import os

2. 参数

参数 详解
path xlsx 文件门路
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

索引为 1

正文完
 0