import re import openpyxl from pathlib import Path import time import sys import os def txt_to_xlsx(): try: print("正在启动覆盖率转换工具...") print("正在搜索目录中的txt文件...") # 获取当前工作目录(兼容打包前后) if getattr(sys, 'frozen', False): # 如果是打包后的exe运行 current_dir = Path(os.path.dirname(sys.executable)) else: # 如果是直接运行Python脚本 current_dir = Path(__file__).parent print(f"当前工作目录: {current_dir}") # 查找当前目录下的所有txt文件 txt_files = list(current_dir.glob("*.txt")) # 检查是否存在txt文件 if not txt_files: print("没有文件,请将txt文件放入当前目录后重试") return print(f"找到 {len(txt_files)} 个txt文件,正在处理第一个文件: {txt_files[0].name}") # 使用找到的第一个txt文件 txt_path = txt_files[0] xlsx_path = current_dir / "coverage_summary.xlsx" text = txt_path.read_text(encoding="utf-8") # 创建Excel工作簿 wb = openpyxl.Workbook() ws = wb.active ws.title = "Coverage Summary" # 表头 - 只包含指标名称和覆盖率 headers = [ "File", "Stmts", "Stmts % Covered", "Branches", "Branches % Covered", "FEC Condition Terms", "FEC Condition Terms % Covered", "FEC Expression Terms", "FEC Expression Terms % Covered", "FSM States", "FSM States % Covered", "FSM Transitions", "FSM Transitions % Covered" ] ws.append(headers) # 按文件分割内容 files = re.split(r"={80}\n=== File: (.+?)\n={80}", text) # 解析每个文件内容 for i in range(1, len(files), 2): file_path = files[i].strip() content = files[i+1] # 提取文件名(去掉路径) file_name = Path(file_path).name # 初始化行数据 row = [file_name] # 定义要提取的指标 metrics = [ "Stmts", "Branches", "FEC Condition Terms", "FEC Expression Terms", "States", # FSM States "Transitions" # FSM Transitions ] # 为每个指标提取数据 for metric in metrics: # 构建正则表达式模式 pattern = rf"^\s*{re.escape(metric)}\b\s+(\d+)\s+\d+\s+\d+\s+([\d\.]+)%?$" # 查找匹配项 match = re.search(pattern, content, flags=re.M) if match: count, percent = match.groups() row.extend([count, f"{percent}%"]) else: # 如果没有找到特定指标,统一填入 "/" row.extend(["/", "/"]) ws.append(row) # 自动调整列宽 for col in ws.columns: max_len = max(len(str(cell.value or "")) for cell in col) ws.column_dimensions[col[0].column_letter].width = max(10, min(50, max_len + 2)) # 保存Excel文件 wb.save(xlsx_path) print(f"完成转换: {xlsx_path}") except Exception as e: print(f"发生错误: {e}") import traceback traceback.print_exc() finally: # 等待10秒防止窗口闪退 print("程序将在10秒后退出...") time.sleep(10) # 直接调用函数,无需传入参数 if __name__ == "__main__": txt_to_xlsx()