report_generate.py 8.2 KB

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