report_generate.py 8.9 KB

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