import re import openpyxl from pathlib import Path def md_to_xlsx(md_path, xlsx_path): text = Path(md_path).read_text(encoding="utf-8") # 分模块 modules = re.split(r"=+\s*\n(.+?)\n=+", text, flags=re.S) # Excel wb = openpyxl.Workbook() ws = wb.active ws.title = "Coverage Summary" # 表头 headers = [ "Module", "Stmts", "Stmts Covered", "Branches", "Branches Covered", "FEC Condition Terms", "FEC Condition Terms Covered", "FEC Expression Terms", "FEC Expression Terms Covered", "States", "States Covered" ] ws.append(headers) metrics = [ "Stmts", "Branches", "FEC Condition Terms", "FEC Expression Terms", "States" ] # 提取数量与覆盖率 def extract_from_line(line): ints = re.findall(r"(\d+)", line) floats = re.findall(r"(\d+\.\d+)", line) count = ints[0] if ints else "/" covered = (floats[-1] + "%") if floats else "/" return count, covered # 解析每个模块内容 for i in range(1, len(modules), 2): module = modules[i].strip() content = modules[i+1] row = [module] for metric in metrics: m = re.search(rf"^\s*{re.escape(metric)}\b.*$", content, flags=re.M) if m: cnt, cov = extract_from_line(m.group(0)) else: cnt, cov = "/", "/" row.extend([cnt, cov]) 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)) wb.save(xlsx_path) print(f"完成转换: {xlsx_path}") # 示例调用 md_to_xlsx( "Coverage Report Summary Data by file.md", "coverage_summary.xlsx" )