report_generate.py 10 KB

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