20260326工作核查excel表

2026年03月26日左右,我工作中处理一部分表格,但是我又担心处理表格存在数据失误,所以在处理完成以后,我需要对139到191的数据进行核查,查看数据是否为我设定数据,下面是正确代码
import os
import pandas as pd

def check_specific_range():
    # --- 配置区域 ---
    TARGET_NAME = "姓名"  # 设定标准姓名
    COLUMN_NAME = "实际测试人"
    START_ROW = 139  # Excel中的起始行号
    END_ROW = 191    # Excel中的结束行号
    
    # 获取当前目录下所有 tet 开头的 xlsx 文件
    files = [f for f in os.listdir('.') if f.startswith('tet') and f.endswith('.xlsx')]
    
    if not files:
        print("未找到 tet 开头的 xlsx 文件。")
        return

    print(f"正在检查 {START_ROW}-{END_ROW} 行,目标姓名: {TARGET_NAME}")
    print("-" * 50)

    for file_name in files:
        try:
            # 读取文件
            df = pd.read_excel(file_name)
            
            # 1. 定位列
            target_col_index = None
            for i, col in enumerate(df.columns):
                if COLUMN_NAME in str(col):
                    target_col_index = i
                    break
            
            if target_col_index is None:
                print(f"[跳过] {file_name} : 未找到 '{COLUMN_NAME}' 列")
                continue

            # 2. 计算 Pandas 索引范围
            # Excel 第 1 行通常是表头(Index 0),所以数据从 Index 0 开始算
            # Excel 第 139 行对应 df.iloc 的索引是 137 (139 - 2)
            # 因为 pandas 默认把第一行作为 column,所以索引偏移是 2
            start_idx = START_ROW - 2
            end_idx = END_ROW - 1  # iloc 是左闭右开,所以指向 191 行需要到 191-2+1
            
            # 提取指定范围的数据(如果文件没那么长,会自动截断)
            subset = df.iloc[start_idx:end_idx, target_col_index]
            
            # 3. 检查是否有非标姓名
            # 清洗数据:转字符串、去空格、去掉空值
            invalid_rows = subset.dropna().astype(str).str.strip()
            mismatches = invalid_rows[invalid_rows != TARGET_NAME]
            
            if not mismatches.empty:
                print(f"❌ 发现异常文件: {file_name}")
                # 打印具体的异常姓名及其在 Excel 中的行号
                for idx, val in mismatches.items():
                    print(f"    第 {idx + 2} 行发现错误姓名: [{val}]")

        except Exception as e:
            print(f"⚠️ 处理 {file_name} 出错: {e}")

if __name__ == "__main__":
    check_specific_range()

  

posted @ 2026-03-26 09:02  kailicard  阅读(10)  评论(0)    收藏  举报