report_generate.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: yq
  4. @time: 2024/11/8
  5. @desc:
  6. """
  7. import os
  8. from typing import Dict
  9. from docx import Document
  10. from docx.enum.text import WD_ALIGN_PARAGRAPH
  11. from docx.oxml import OxmlElement
  12. from docx.oxml.ns import qn
  13. from docx.shared import Inches
  14. from commom import GeneralException, f_get_datetime
  15. from config import BaseConfig
  16. from entitys import MetricFucEntity
  17. from enums import ResultCodesEnum, PlaceholderPrefixEnum
  18. class Report():
  19. @staticmethod
  20. def _merge_cell_column(pre_cell, curr_cell):
  21. if curr_cell.text == pre_cell.text:
  22. column_name = curr_cell.text
  23. pre_cell.merge(curr_cell)
  24. pre_cell.text = column_name
  25. for run in pre_cell.paragraphs[0].runs:
  26. run.bold = True
  27. pre_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
  28. @staticmethod
  29. def _set_table_singleBoard(table):
  30. # 将table 的所有单元格四个边设置为 0.5 镑, 黑色, 实线
  31. def _set_table_boarder(table, **kwargs):
  32. """
  33. Set table`s border
  34. Usage:
  35. set_table_border(
  36. cell,
  37. top={"sz": 12, "val": "single", "color": "#FF0000"},
  38. bottom={"sz": 12, "color": "#00FF00", "val": "single"},
  39. left={"sz": 24, "val": "dashed"},
  40. right={"sz": 12, "val": "dashed"},
  41. )
  42. """
  43. borders = OxmlElement('w:tblBorders')
  44. for tag in ('bottom', 'top', 'left', 'right', 'insideV', 'insideH'):
  45. edge_data = kwargs.get(tag)
  46. if edge_data:
  47. any_border = OxmlElement(f'w:{tag}')
  48. for key in ["sz", "val", "color", "space", "shadow"]:
  49. if key in edge_data:
  50. any_border.set(qn(f'w:{key}'), str(edge_data[key]))
  51. borders.append(any_border)
  52. table._tbl.tblPr.append(borders)
  53. return _set_table_boarder(
  54. table,
  55. top={"sz": 4, "val": "single", "color": "#000000"},
  56. bottom={"sz": 4, "val": "single", "color": "#000000"},
  57. left={"sz": 4, "val": "single", "color": "#000000"},
  58. right={"sz": 4, "val": "single", "color": "#000000"},
  59. insideV={"sz": 4, "val": "single", "color": "#000000"},
  60. insideH={"sz": 4, "val": "single", "color": "#000000"}
  61. )
  62. @staticmethod
  63. def _get_placeholder(placeholder_prefix_enum: PlaceholderPrefixEnum, metric_code: str):
  64. return "{{" + f"{placeholder_prefix_enum.value}{metric_code}" + "}}"
  65. @staticmethod
  66. def _fill_value_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucEntity]):
  67. # 替换指标
  68. for paragraph in doc.paragraphs:
  69. text = paragraph.text
  70. for metric_code, metric_fuc_entity in metric_value_dict.items():
  71. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.VALUE, metric_code)
  72. metric_value = metric_fuc_entity.value
  73. if metric_value is None:
  74. continue
  75. text = text.replace(placeholder, metric_value)
  76. # 段落中多个runs时执行,最后一个run改成替换好的文本,其他run置空
  77. if len(paragraph.runs[:-1]) > 0:
  78. for run in paragraph.runs[:-1]:
  79. run.text = ''
  80. paragraph.runs[-1].text = text
  81. @staticmethod
  82. def _fill_table_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucEntity]):
  83. # 替换表格
  84. for paragraph in doc.paragraphs:
  85. for metric_code, metric_fuc_entity in metric_value_dict.items():
  86. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.TABLE, metric_code)
  87. metric_table = metric_fuc_entity.table
  88. if metric_table is None:
  89. continue
  90. if not placeholder in paragraph.text:
  91. continue
  92. # 清除占位符
  93. for run in paragraph.runs:
  94. run.text = run.text.replace(placeholder, "")
  95. table = doc.add_table(rows=metric_table.shape[0] + 1, cols=metric_table.shape[1])
  96. table.alignment = WD_ALIGN_PARAGRAPH.CENTER
  97. paragraph._element.addnext(table._element)
  98. # 列名
  99. for column_idx, column_name in enumerate(metric_table.columns):
  100. cell = table.cell(0, column_idx)
  101. cell.text = str(column_name)
  102. for run in cell.paragraphs[0].runs:
  103. run.bold = True
  104. cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
  105. # 合并相同的列名
  106. if column_idx != 0 and BaseConfig.merge_table_column:
  107. pre_cell = table.cell(0, column_idx - 1)
  108. Report._merge_cell_column(pre_cell, cell)
  109. # 值
  110. for row_idx, row in metric_table.iterrows():
  111. for column_idx, value in enumerate(row):
  112. cell = table.cell(row_idx + 1, column_idx)
  113. cell.text = str(value)
  114. cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
  115. Report._set_table_singleBoard(table)
  116. @staticmethod
  117. def _fill_image_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucEntity]):
  118. # 替换图片
  119. for paragraph in doc.paragraphs:
  120. for metric_code, metric_fuc_entity in metric_value_dict.items():
  121. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.IMAGE, metric_code)
  122. image_path = metric_fuc_entity.image_path
  123. if image_path is None:
  124. continue
  125. if not placeholder in paragraph.text:
  126. continue
  127. if not os.path.exists(image_path):
  128. raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"文件【{image_path}】不存在")
  129. # 清除占位符
  130. for run in paragraph.runs:
  131. if placeholder not in run.text:
  132. continue
  133. run.text = run.text.replace(placeholder, "")
  134. run.add_picture(image_path, width=Inches(5))
  135. @staticmethod
  136. def generate_report(metric_value_dict: Dict[str, MetricFucEntity], template_path: str):
  137. if os.path.exists(template_path):
  138. doc = Document(template_path)
  139. else:
  140. raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"监控模板文件【{template_path}】不存在")
  141. Report._fill_value_placeholder(doc, metric_value_dict)
  142. Report._fill_table_placeholder(doc, metric_value_dict)
  143. Report._fill_image_placeholder(doc, metric_value_dict)
  144. new_path = template_path.replace(".docx", f"{f_get_datetime()}.docx")
  145. doc.save(f"./{new_path}")
  146. if __name__ == "__main__":
  147. pass