report_generate.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. import pandas as pd
  10. from docx import Document
  11. from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
  12. from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
  13. from docx.oxml import OxmlElement
  14. from docx.oxml.ns import qn
  15. from docx.shared import Inches, Cm, Pt
  16. from commom import GeneralException, f_get_datetime
  17. from config import BaseConfig
  18. from entitys import MetricFucResultEntity
  19. from enums import ResultCodesEnum, PlaceholderPrefixEnum
  20. class Report():
  21. @staticmethod
  22. def _set_cell_width(table, table_cell_width):
  23. # 固定宽度
  24. for column in table.columns:
  25. if table_cell_width is not None:
  26. column.width = Cm(table_cell_width)
  27. continue
  28. # 自动调整宽度
  29. max_text_len_list = []
  30. a4_width = 21 - 2 # * 3.18
  31. for column in table.columns:
  32. max_text_len = 0
  33. for cell in column.cells:
  34. cell_text_len = Report._get_text_length(cell.text)
  35. max_text_len = cell_text_len if cell_text_len > max_text_len else max_text_len
  36. max_text_len_list.append(max_text_len)
  37. # 按比例分配宽度
  38. cell_width_unit = a4_width / sum(max_text_len_list)
  39. cell_widths = [c * cell_width_unit for c in max_text_len_list]
  40. min_cell_width = 1
  41. # 限制最小宽度
  42. adjusted_cell_widths = [max(c, min_cell_width) for c in cell_widths]
  43. adjusted_width = sum(adjusted_cell_widths)
  44. if adjusted_width > a4_width:
  45. excess_width = adjusted_width - a4_width
  46. excess_width_per_column = excess_width / len(table.columns)
  47. # 减去多的宽度
  48. adjusted_cell_widths = [max(min_cell_width, c - excess_width_per_column) for c in
  49. adjusted_cell_widths]
  50. for idx, column in enumerate(table.columns):
  51. column.width = Cm(adjusted_cell_widths[idx])
  52. @staticmethod
  53. def _set_cell_format(cell, font_size=None):
  54. for paragraph in cell.paragraphs:
  55. paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
  56. # 首行缩进改0
  57. paragraph_format = paragraph.paragraph_format
  58. paragraph_format.first_line_indent = 0
  59. paragraph_format.element.pPr.ind.set(qn("w:firstLineChars"), '0')
  60. for run in paragraph.runs:
  61. # 判断文本是否包含中文
  62. if any('\u4e00' <= char <= '\u9fff' for char in run.text):
  63. run.font.name = '宋体' # 设置中文字体为宋体
  64. else:
  65. run.font.name = 'Times New Roman' # 设置英文字体为Times New Roman
  66. if font_size is not None:
  67. run.font.size = Pt(font_size)
  68. cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
  69. @staticmethod
  70. def _merge_cell_column(pre_cell, curr_cell, table_font_size, table_cell_width):
  71. if curr_cell.text == pre_cell.text:
  72. column_name = curr_cell.text
  73. pre_cell.merge(curr_cell)
  74. pre_cell.text = column_name
  75. for run in pre_cell.paragraphs[0].runs:
  76. run.bold = True
  77. Report._set_cell_format(pre_cell, table_font_size)
  78. @staticmethod
  79. def _set_table_singleBoard(table):
  80. # 将table 的所有单元格四个边设置为 0.5 镑, 黑色, 实线
  81. def _set_table_boarder(table, **kwargs):
  82. """
  83. Set table`s border
  84. Usage:
  85. set_table_border(
  86. cell,
  87. top={"sz": 12, "val": "single", "color": "#FF0000"},
  88. bottom={"sz": 12, "color": "#00FF00", "val": "single"},
  89. left={"sz": 24, "val": "dashed"},
  90. right={"sz": 12, "val": "dashed"},
  91. )
  92. """
  93. borders = OxmlElement('w:tblBorders')
  94. for tag in ('bottom', 'top', 'left', 'right', 'insideV', 'insideH'):
  95. edge_data = kwargs.get(tag)
  96. if edge_data:
  97. any_border = OxmlElement(f'w:{tag}')
  98. for key in ["sz", "val", "color", "space", "shadow"]:
  99. if key in edge_data:
  100. any_border.set(qn(f'w:{key}'), str(edge_data[key]))
  101. borders.append(any_border)
  102. table._tbl.tblPr.append(borders)
  103. return _set_table_boarder(
  104. table,
  105. top={"sz": 4, "val": "single", "color": "#000000"},
  106. bottom={"sz": 4, "val": "single", "color": "#000000"},
  107. left={"sz": 4, "val": "single", "color": "#000000"},
  108. right={"sz": 4, "val": "single", "color": "#000000"},
  109. insideV={"sz": 4, "val": "single", "color": "#000000"},
  110. insideH={"sz": 4, "val": "single", "color": "#000000"}
  111. )
  112. @staticmethod
  113. def _get_placeholder(placeholder_prefix_enum: PlaceholderPrefixEnum, metric_code: str):
  114. return "{{" + f"{placeholder_prefix_enum.value}{metric_code}" + "}}"
  115. @staticmethod
  116. def _fill_value_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucResultEntity]):
  117. # 替换指标
  118. for paragraph in doc.paragraphs:
  119. text = paragraph.text
  120. for metric_code, metric_fuc_entity in metric_value_dict.items():
  121. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.VALUE, metric_code)
  122. metric_value = metric_fuc_entity.value
  123. if metric_value is None:
  124. continue
  125. text = text.replace(placeholder, str(metric_value))
  126. # 段落中多个runs时执行,最后一个run改成替换好的文本,其他run置空
  127. if len(paragraph.runs[:-1]) > 0:
  128. for run in paragraph.runs[:-1]:
  129. run.text = ''
  130. paragraph.runs[-1].text = text
  131. @staticmethod
  132. def _get_text_length(text):
  133. return sum(2 if '\u4e00' <= char <= '\u9fff' else 1 for char in text)
  134. @staticmethod
  135. def _fill_table_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucResultEntity]):
  136. # 替换表格
  137. for paragraph in doc.paragraphs:
  138. for metric_code, metric_fuc_entity in metric_value_dict.items():
  139. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.TABLE, metric_code)
  140. metric_table = metric_fuc_entity.table
  141. table_font_size = metric_fuc_entity.table_font_size
  142. table_autofit = metric_fuc_entity.table_autofit
  143. table_cell_width = metric_fuc_entity.table_cell_width
  144. if metric_table is None:
  145. continue
  146. if not placeholder in paragraph.text:
  147. continue
  148. # 清除占位符
  149. for run in paragraph.runs:
  150. run.text = run.text.replace(placeholder, "")
  151. table = doc.add_table(rows=metric_table.shape[0] + 1, cols=metric_table.shape[1])
  152. table.alignment = WD_TABLE_ALIGNMENT.CENTER
  153. paragraph._element.addnext(table._element)
  154. # 列名
  155. for column_idx, column_name in enumerate(metric_table.columns):
  156. cell = table.cell(0, column_idx)
  157. cell.text = str(column_name)
  158. for run in cell.paragraphs[0].runs:
  159. run.bold = True
  160. Report._set_cell_format(cell, table_font_size)
  161. # 合并相同的列名
  162. if column_idx != 0 and BaseConfig.merge_table_column:
  163. pre_cell = table.cell(0, column_idx - 1)
  164. Report._merge_cell_column(pre_cell, cell, table_font_size, table_cell_width)
  165. # 值
  166. for row_idx, row in metric_table.iterrows():
  167. for column_idx, value in enumerate(row):
  168. cell = table.cell(row_idx + 1, column_idx)
  169. value = str(value) if pd.notna(value) else '/'
  170. cell.text = str(value)
  171. Report._set_cell_format(cell, table_font_size)
  172. # 合并第一行数据也为列的情况
  173. if row_idx == 0:
  174. Report._merge_cell_column(table.cell(0, column_idx), cell, table_font_size,
  175. table_cell_width)
  176. Report._set_table_singleBoard(table)
  177. Report._set_cell_width(table, table_cell_width)
  178. # 禁止自动调整表格
  179. if len(metric_table.columns) <= 20 and not table_autofit:
  180. table.autofit = False
  181. @staticmethod
  182. def _fill_image_placeholder(doc: Document, metric_value_dict: Dict[str, MetricFucResultEntity]):
  183. # 替换图片
  184. for paragraph in doc.paragraphs:
  185. for metric_code, metric_fuc_entity in metric_value_dict.items():
  186. placeholder = Report._get_placeholder(PlaceholderPrefixEnum.IMAGE, metric_code)
  187. image_path = metric_fuc_entity.image_path
  188. image_size = metric_fuc_entity.image_size
  189. if image_path is None:
  190. continue
  191. if not placeholder in paragraph.text:
  192. continue
  193. if isinstance(image_path, str):
  194. image_path = [image_path]
  195. for path in image_path:
  196. if not os.path.exists(path):
  197. raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"文件【{image_path}】不存在")
  198. # 清除占位符
  199. for run in paragraph.runs:
  200. if placeholder not in run.text:
  201. continue
  202. run.text = run.text.replace(placeholder, "")
  203. for path in image_path:
  204. run.add_picture(path, width=Inches(image_size))
  205. @staticmethod
  206. def generate_report(metric_value_dict: Dict[str, MetricFucResultEntity], template_path: str, save_path=None):
  207. if os.path.exists(template_path):
  208. doc = Document(template_path)
  209. else:
  210. raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"监控模板文件【{template_path}】不存在")
  211. Report._fill_value_placeholder(doc, metric_value_dict)
  212. Report._fill_table_placeholder(doc, metric_value_dict)
  213. Report._fill_image_placeholder(doc, metric_value_dict)
  214. new_path = template_path.replace(".docx", f"{f_get_datetime()}.docx")
  215. if save_path is not None:
  216. new_path = save_path
  217. doc.save(f"./{new_path}")
  218. if __name__ == "__main__":
  219. pass