续接Python之txt数据预定替换word预定义定位标记生成word报告(一)
https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=7482354347595088424
Python之txt数据预定替换word预定义定位标记生成word报告(二)
https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=7482355993293160994
Python之txt数据预定替换word预定义定位标记生成word报告(三)
https://www.toutiao.com/article/7482357201093378594/
本部分介绍“报告生成模块 - ReportGenerator类”,python代码如下:
class ReportGenerator:
"""报告生成器,核心功能:
1. 关联模板数据与文件数据
2. 执行精准内容替换
"""
def __init__(self):
self.analyzer = TemplateAnalyzer()
self.table_map = self.analyzer.analyze(start_table=7, end_table=33)
self.doc = Document(TEMPLATE_PATH)
def _update_cell(self, cell, new_text):
"""安全更新单元格内容(保留格式)
:param cell: 单元格对象
:param new_text: 新内容
"""
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.text = ""
if cell.paragraphs:
cell.paragraphs[0].add_run(new_text)
else:
cell.add_paragraph(new_text)
def process_files(self):
"""执行全量数据替换"""
print("\n 开始处理文件...")
for filename in os.listdir(TXT_DIR):
if not (ip_match := re.search(r"(\d+\.\d+\.\d+\.\d+)-checkOS-", filename)):
print(f"[SKIP] 跳过无效文件:{filename}")
continue
ip = ip_match.group(1)
if ip not in self.table_map:
print(f"! 未找到IP {ip} 的配置表格")
continue
file_path = os.path.join(TXT_DIR, filename)
data = DataProcessor.extract_data(file_path)
for table_idx, marker_positions in self.table_map[ip].items():
print(f"\n处理表格{table_idx + 1}:")
try:
table = self.doc.tables[table_idx]
except IndexError:
print(f"! 表格{table_idx + 1}不存在")
continue
for marker, positions in marker_positions.items():
content = data.get(marker, "[数据缺失]")
for row_idx, cell_idx in positions:
try:
cell = table.cell(row_idx, cell_idx)
self._update_cell(cell, content)
print(f" 已更新:行{row_idx + 1}列{cell_idx + 1}的{marker}")
except:
print(f"! 坐标错误:行{row_idx}列{cell_idx}")
self.doc.save(OUTPUT_PATH)
print(f"\n 报告生成完成:{os.path.abspath(OUTPUT_PATH)}")
- **类定义**:`ReportGenerator`类负责生成最终报告。
- **构造函数`__init__`**:实例化`TemplateAnalyzer`类并分析模板,获取IP - 表格 - 标记的映射关系,同时加载Word模板。
- **`_update_cell`方法**:安全地更新单元格内容,保留原有格式。
- **`process_files`方法**:遍历TXT文件存储目录中的所有文件,提取文件名中的IP地址,验证IP是否在模板映射关系中存在。如果存在,则提取TXT文件数据,并根据映射关系将数据填充到Word模板的相应单元格中,最后保存生成的报告。