pyreportkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. pyreportkit-0.1.0.dist-info/METADATA +187 -0
  2. pyreportkit-0.1.0.dist-info/RECORD +222 -0
  3. pyreportkit-0.1.0.dist-info/WHEEL +5 -0
  4. pyreportkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. pyreportkit-0.1.0.dist-info/top_level.txt +1 -0
  6. reportkit/__init__.py +0 -0
  7. reportkit/components/__init__.py +45 -0
  8. reportkit/components/document/__init__.py +6 -0
  9. reportkit/components/document/footer.py +12 -0
  10. reportkit/components/document/header.py +12 -0
  11. reportkit/components/document/page.py +18 -0
  12. reportkit/components/document/report.py +12 -0
  13. reportkit/components/information/__init__.py +4 -0
  14. reportkit/components/information/info_grid.py +23 -0
  15. reportkit/components/information/key_value.py +28 -0
  16. reportkit/components/layout/__init__.py +9 -0
  17. reportkit/components/layout/box.py +10 -0
  18. reportkit/components/layout/column.py +15 -0
  19. reportkit/components/layout/divider.py +10 -0
  20. reportkit/components/layout/grid.py +12 -0
  21. reportkit/components/layout/row.py +15 -0
  22. reportkit/components/layout/section.py +10 -0
  23. reportkit/components/layout/spacer.py +12 -0
  24. reportkit/components/media/__init__.py +4 -0
  25. reportkit/components/media/chart.py +14 -0
  26. reportkit/components/media/image.py +25 -0
  27. reportkit/components/pagination/__init__.py +5 -0
  28. reportkit/components/pagination/page_break.py +10 -0
  29. reportkit/components/pagination/page_count.py +10 -0
  30. reportkit/components/pagination/page_number.py +21 -0
  31. reportkit/components/table/__init__.py +7 -0
  32. reportkit/components/table/cell.py +27 -0
  33. reportkit/components/table/column.py +29 -0
  34. reportkit/components/table/row.py +25 -0
  35. reportkit/components/table/style.py +18 -0
  36. reportkit/components/table/table.py +27 -0
  37. reportkit/components/typography/__init__.py +6 -0
  38. reportkit/components/typography/heading.py +13 -0
  39. reportkit/components/typography/rich_text.py +23 -0
  40. reportkit/components/typography/text.py +12 -0
  41. reportkit/components/typography/text_span.py +24 -0
  42. reportkit/core/__init__.py +4 -0
  43. reportkit/core/component.py +12 -0
  44. reportkit/core/container.py +66 -0
  45. reportkit/core/exceptions.py +0 -0
  46. reportkit/core/factory.py +53 -0
  47. reportkit/core/registry.py +50 -0
  48. reportkit/core/serializer.py +90 -0
  49. reportkit/exporters/__init__.py +0 -0
  50. reportkit/exporters/base.py +17 -0
  51. reportkit/exporters/excel/__init__.py +8 -0
  52. reportkit/exporters/excel/exceptions.py +4 -0
  53. reportkit/exporters/excel/exporter.py +68 -0
  54. reportkit/exporters/excel/renderers/__init__.py +34 -0
  55. reportkit/exporters/excel/renderers/base.py +27 -0
  56. reportkit/exporters/excel/renderers/information.py +55 -0
  57. reportkit/exporters/excel/renderers/layout/__init__.py +7 -0
  58. reportkit/exporters/excel/renderers/layout/columns.py +48 -0
  59. reportkit/exporters/excel/renderers/layout/data.py +46 -0
  60. reportkit/exporters/excel/renderers/layout/page.py +24 -0
  61. reportkit/exporters/excel/renderers/layout/spacing.py +30 -0
  62. reportkit/exporters/excel/renderers/layout/stack.py +13 -0
  63. reportkit/exporters/excel/renderers/media.py +46 -0
  64. reportkit/exporters/excel/renderers/registry.py +22 -0
  65. reportkit/exporters/excel/renderers/table/__init__.py +4 -0
  66. reportkit/exporters/excel/renderers/table/cells.py +17 -0
  67. reportkit/exporters/excel/renderers/table/data.py +38 -0
  68. reportkit/exporters/excel/renderers/table/renderer.py +64 -0
  69. reportkit/exporters/excel/renderers/table/widths.py +29 -0
  70. reportkit/exporters/excel/renderers/text.py +40 -0
  71. reportkit/exporters/excel/styles.py +130 -0
  72. reportkit/exporters/excel/values/__init__.py +5 -0
  73. reportkit/exporters/excel/values/cells.py +60 -0
  74. reportkit/exporters/excel/values/components.py +16 -0
  75. reportkit/exporters/excel/values/formats.py +31 -0
  76. reportkit/exporters/excel/values/numbers.py +19 -0
  77. reportkit/exporters/excel/workbook/__init__.py +5 -0
  78. reportkit/exporters/excel/workbook/data.py +48 -0
  79. reportkit/exporters/excel/workbook/formatted.py +63 -0
  80. reportkit/exporters/excel/workbook/styles.py +27 -0
  81. reportkit/exporters/excel/workbook/workbook.py +65 -0
  82. reportkit/exporters/excel/worksheet/__init__.py +5 -0
  83. reportkit/exporters/excel/worksheet/borders.py +30 -0
  84. reportkit/exporters/excel/worksheet/cells.py +38 -0
  85. reportkit/exporters/excel/worksheet/constants.py +12 -0
  86. reportkit/exporters/excel/worksheet/data.py +51 -0
  87. reportkit/exporters/excel/worksheet/formatted.py +158 -0
  88. reportkit/exporters/excel/worksheet/page.py +23 -0
  89. reportkit/exporters/html/__init__.py +6 -0
  90. reportkit/exporters/html/assets.py +87 -0
  91. reportkit/exporters/html/direction.py +15 -0
  92. reportkit/exporters/html/engine.py +37 -0
  93. reportkit/exporters/html/exporter.py +38 -0
  94. reportkit/exporters/html/page/__init__.py +3 -0
  95. reportkit/exporters/html/page/components.py +47 -0
  96. reportkit/exporters/html/page/margins.py +24 -0
  97. reportkit/exporters/html/page/numbering.py +31 -0
  98. reportkit/exporters/html/page/resolver.py +37 -0
  99. reportkit/exporters/html/page/running.py +30 -0
  100. reportkit/exporters/html/page/styles.py +22 -0
  101. reportkit/exporters/html/page/validator.py +76 -0
  102. reportkit/exporters/html/registry.py +45 -0
  103. reportkit/exporters/html/renderers/__init__.py +37 -0
  104. reportkit/exporters/html/renderers/base.py +20 -0
  105. reportkit/exporters/html/renderers/document/__init__.py +6 -0
  106. reportkit/exporters/html/renderers/document/footer.py +18 -0
  107. reportkit/exporters/html/renderers/document/header.py +18 -0
  108. reportkit/exporters/html/renderers/document/page.py +17 -0
  109. reportkit/exporters/html/renderers/document/report.py +16 -0
  110. reportkit/exporters/html/renderers/information/__init__.py +4 -0
  111. reportkit/exporters/html/renderers/information/info_grid.py +26 -0
  112. reportkit/exporters/html/renderers/information/key_value.py +18 -0
  113. reportkit/exporters/html/renderers/layout/__init__.py +9 -0
  114. reportkit/exporters/html/renderers/layout/box.py +17 -0
  115. reportkit/exporters/html/renderers/layout/column.py +41 -0
  116. reportkit/exporters/html/renderers/layout/divider.py +16 -0
  117. reportkit/exporters/html/renderers/layout/grid.py +48 -0
  118. reportkit/exporters/html/renderers/layout/row.py +35 -0
  119. reportkit/exporters/html/renderers/layout/section.py +17 -0
  120. reportkit/exporters/html/renderers/layout/spacer.py +18 -0
  121. reportkit/exporters/html/renderers/media/__init__.py +3 -0
  122. reportkit/exporters/html/renderers/media/image.py +18 -0
  123. reportkit/exporters/html/renderers/pagination/__init__.py +4 -0
  124. reportkit/exporters/html/renderers/pagination/page_break.py +15 -0
  125. reportkit/exporters/html/renderers/pagination/page_number.py +15 -0
  126. reportkit/exporters/html/renderers/table/__init__.py +4 -0
  127. reportkit/exporters/html/renderers/table/cell.py +77 -0
  128. reportkit/exporters/html/renderers/table/table.py +69 -0
  129. reportkit/exporters/html/renderers/typography/__init__.py +5 -0
  130. reportkit/exporters/html/renderers/typography/heading.py +18 -0
  131. reportkit/exporters/html/renderers/typography/rich_text.py +28 -0
  132. reportkit/exporters/html/renderers/typography/text.py +16 -0
  133. reportkit/exporters/html/static/base.css +45 -0
  134. reportkit/exporters/html/static/information.css +83 -0
  135. reportkit/exporters/html/static/layout.css +81 -0
  136. reportkit/exporters/html/static/media.css +10 -0
  137. reportkit/exporters/html/static/pdf.css +96 -0
  138. reportkit/exporters/html/static/print.css +91 -0
  139. reportkit/exporters/html/static/table.css +222 -0
  140. reportkit/exporters/html/static/tokens.css +68 -0
  141. reportkit/exporters/html/static/typography.css +54 -0
  142. reportkit/exporters/html/styles.py +167 -0
  143. reportkit/exporters/html/templates/components/document/footer.html +3 -0
  144. reportkit/exporters/html/templates/components/document/header.html +3 -0
  145. reportkit/exporters/html/templates/components/document/page.html +8 -0
  146. reportkit/exporters/html/templates/components/document/report.html +3 -0
  147. reportkit/exporters/html/templates/components/information/info_grid.html +6 -0
  148. reportkit/exporters/html/templates/components/information/key_value.html +9 -0
  149. reportkit/exporters/html/templates/components/layout/box.html +3 -0
  150. reportkit/exporters/html/templates/components/layout/column.html +3 -0
  151. reportkit/exporters/html/templates/components/layout/divider.html +1 -0
  152. reportkit/exporters/html/templates/components/layout/grid.html +3 -0
  153. reportkit/exporters/html/templates/components/layout/row.html +3 -0
  154. reportkit/exporters/html/templates/components/layout/section.html +3 -0
  155. reportkit/exporters/html/templates/components/layout/spacer.html +1 -0
  156. reportkit/exporters/html/templates/components/media/image.html +8 -0
  157. reportkit/exporters/html/templates/components/pagination/page_break.html +1 -0
  158. reportkit/exporters/html/templates/components/pagination/page_number.html +4 -0
  159. reportkit/exporters/html/templates/components/table/cell.html +7 -0
  160. reportkit/exporters/html/templates/components/table/table.html +34 -0
  161. reportkit/exporters/html/templates/components/typography/heading.html +1 -0
  162. reportkit/exporters/html/templates/components/typography/rich_text.html +5 -0
  163. reportkit/exporters/html/templates/components/typography/text.html +1 -0
  164. reportkit/exporters/html/templates/document.html +17 -0
  165. reportkit/exporters/html/templates.py +30 -0
  166. reportkit/exporters/json.py +0 -0
  167. reportkit/exporters/pdf/__init__.py +8 -0
  168. reportkit/exporters/pdf/conversion.py +104 -0
  169. reportkit/exporters/pdf/dependencies.py +12 -0
  170. reportkit/exporters/pdf/exceptions.py +4 -0
  171. reportkit/exporters/pdf/exporter.py +16 -0
  172. reportkit/exporters/pdf/resources/__init__.py +4 -0
  173. reportkit/exporters/pdf/resources/fetcher.py +37 -0
  174. reportkit/exporters/pdf/resources/policy.py +60 -0
  175. reportkit/exporters/registry.py +50 -0
  176. reportkit/exporters/word/__init__.py +8 -0
  177. reportkit/exporters/word/document/__init__.py +4 -0
  178. reportkit/exporters/word/document/document.py +74 -0
  179. reportkit/exporters/word/document/engine.py +71 -0
  180. reportkit/exporters/word/exceptions.py +4 -0
  181. reportkit/exporters/word/exporter.py +32 -0
  182. reportkit/exporters/word/renderers/__init__.py +24 -0
  183. reportkit/exporters/word/renderers/base.py +56 -0
  184. reportkit/exporters/word/renderers/information.py +30 -0
  185. reportkit/exporters/word/renderers/layout/__init__.py +6 -0
  186. reportkit/exporters/word/renderers/layout/columns.py +82 -0
  187. reportkit/exporters/word/renderers/layout/page.py +38 -0
  188. reportkit/exporters/word/renderers/layout/spacing.py +33 -0
  189. reportkit/exporters/word/renderers/layout/stack.py +50 -0
  190. reportkit/exporters/word/renderers/media.py +49 -0
  191. reportkit/exporters/word/renderers/registry.py +22 -0
  192. reportkit/exporters/word/renderers/table/__init__.py +3 -0
  193. reportkit/exporters/word/renderers/table/cells.py +39 -0
  194. reportkit/exporters/word/renderers/table/renderer.py +95 -0
  195. reportkit/exporters/word/renderers/table/widths.py +12 -0
  196. reportkit/exporters/word/renderers/text.py +40 -0
  197. reportkit/exporters/word/styles/__init__.py +3 -0
  198. reportkit/exporters/word/styles/text.py +90 -0
  199. reportkit/exporters/word/styles/xml.py +147 -0
  200. reportkit/exporters/word/values.py +36 -0
  201. reportkit/formatting/__init__.py +0 -0
  202. reportkit/formatting/cell.py +12 -0
  203. reportkit/formatting/cells.py +41 -0
  204. reportkit/formatting/values.py +106 -0
  205. reportkit/rendering/__init__.py +0 -0
  206. reportkit/rendering/context.py +31 -0
  207. reportkit/rendering/table.py +56 -0
  208. reportkit/rendering/tracks.py +51 -0
  209. reportkit/rendering/visitor.py +55 -0
  210. reportkit/report.py +0 -0
  211. reportkit/styles/__init__.py +0 -0
  212. reportkit/styles/borders.py +6 -0
  213. reportkit/styles/style.py +117 -0
  214. reportkit/styles/table.py +37 -0
  215. reportkit/styles/theme.py +45 -0
  216. reportkit/styles/tokens.py +29 -0
  217. reportkit/validators/__init__.py +3 -0
  218. reportkit/validators/table/__init__.py +3 -0
  219. reportkit/validators/table/cell.py +38 -0
  220. reportkit/validators/table/column.py +62 -0
  221. reportkit/validators/table/row.py +37 -0
  222. reportkit/validators/table/table.py +63 -0
@@ -0,0 +1,64 @@
1
+ from .....rendering.table import get_entries, header_text, place_cells
2
+ from .....styles.style import Style
3
+ from .....styles.table import get_row_style, table_styles
4
+ from .....styles.tokens import token
5
+ from .....validators.table.table import TableValidator
6
+ from ...exceptions import ExcelExportError
7
+ from .cells import prepare_entry
8
+ from .widths import get_widths, spans
9
+
10
+
11
+ class TableRenderer:
12
+ """
13
+ Render a Table in the formatted mode: caption, header, prepared rows and footer, sized and framed like the PDF.
14
+ """
15
+
16
+ def render(self, component, context, engine, region):
17
+ """
18
+ Write the table rows in the order they arrive and return the rows used.
19
+ """
20
+ styles, occupied, widths = table_styles(context.resolve_style(component)), set(), get_widths(component, engine, region)
21
+ row = region.row + self.render_caption(component, context, engine, region)
22
+ row += self.render_header(component, engine, region.below(row - region.row), styles, widths)
23
+ for index, table_row in enumerate(component.rows):
24
+ TableValidator.validate_row(table_row)
25
+ row += self.render_row(component, table_row, index, engine, region.below(row - region.row), styles, widths, occupied)
26
+ if component.footer:
27
+ row += self.render_row(component, component.footer, 0, engine, region.below(row - region.row), styles, widths, occupied)
28
+ if not component.table_style.ruled:
29
+ engine.sheet.outline(region.row, region.column, sum(widths), row - region.row, styles["frame"])
30
+ return row - region.row
31
+
32
+ def render_caption(self, component, context, engine, region):
33
+ """
34
+ Write the table caption across the region when the table has one.
35
+ """
36
+ if not component.header:
37
+ return 0
38
+ engine.sheet.place(region.row, region.column, region.width, component.header, Style(font_weight=700, font_size=token("--rk-font-lg")).merge(context.resolve_style(component)))
39
+ return 1
40
+
41
+ def render_header(self, component, engine, region, styles, widths):
42
+ """
43
+ Write the column titles and subtitles, repeated on printed pages when requested.
44
+ """
45
+ if not component.table_style.show_header:
46
+ return 0
47
+ style = styles["header"].merge(styles["ruled"]) if component.table_style.ruled else styles["header"]
48
+ for column, (start, width) in zip(component.columns, spans(region, widths)):
49
+ engine.sheet.place(region.row, start, width, header_text(column, "\n"), style.merge(Style(text_align=column.header_align or column.align)), padding=10)
50
+ if component.table_style.repeat_header:
51
+ engine.sheet.repeat_rows(region.row)
52
+ return 1
53
+
54
+ def render_row(self, component, table_row, index, engine, region, styles, widths, occupied):
55
+ """
56
+ Write one prepared row, merging cells that span columns or rows, and return the single row it starts.
57
+ """
58
+ row_style, starts = get_row_style(component, table_row, index, styles), spans(region, widths)
59
+ for column, entry, colspan, rowspan in place_cells(get_entries(component, table_row), 0, region.row, occupied):
60
+ if column + colspan > len(widths):
61
+ raise ExcelExportError(f"A table row has more cells than the table's {len(widths)} columns.")
62
+ value, cell_style, cell_format = prepare_entry(entry, engine)
63
+ engine.sheet.place(region.row, starts[column][0], sum(widths[column:column + colspan]), value, row_style.merge(cell_style), cell_format, height=rowspan, padding=10)
64
+ return 1
@@ -0,0 +1,29 @@
1
+ from .....rendering.tracks import column_tracks, distribute, track_shares
2
+
3
+
4
+ def get_widths(component, engine, region):
5
+ """
6
+ Share the region between the table columns in whole grid columns.
7
+ """
8
+ return distribute(track_shares(column_tracks(component.columns), engine.sheet.content_pixels), region.width)
9
+
10
+
11
+ def spans(region, widths):
12
+ """
13
+ Return the first grid column and width of every table column.
14
+ """
15
+ return [(region.column + sum(widths[:index]), width) for index, width in enumerate(widths)]
16
+
17
+
18
+ def width_characters(column):
19
+ """
20
+ Convert a declared column width into Excel characters for data sheets, or estimate it from the header.
21
+ """
22
+ width = column.width or ""
23
+ if width.endswith("%"):
24
+ return round(float(width[:-1]) * 1.1, 1)
25
+ if width.endswith("px"):
26
+ return round(float(width[:-2]) / 7, 1)
27
+ if width.endswith("mm"):
28
+ return round(float(width[:-2]) * 0.55, 1)
29
+ return min(40, max(10, len(column.title), len(column.subtitle or "")) + 4)
@@ -0,0 +1,40 @@
1
+ from ....components.typography import Heading
2
+ from ....styles.style import Style
3
+ from ....styles.tokens import token
4
+ from ..values import cell_value, component_text
5
+
6
+ HEADING_SIZES = {1: "--rk-font-2xl", 2: "--rk-font-xl", 3: "--rk-font-lg"}
7
+
8
+
9
+ class TextRenderer:
10
+ """
11
+ Render Text, Heading and RichText as one merged cell across the region.
12
+ """
13
+
14
+ def render(self, component, context, engine, region):
15
+ """
16
+ Write the text and return the single row it uses.
17
+ """
18
+ engine.sheet.place(region.row, region.column, region.width, cell_value(component_text(component)), self.get_style(component, context))
19
+ return 1
20
+
21
+ def get_style(self, component, context):
22
+ """
23
+ Use the component style, with the heading defaults for headings.
24
+ """
25
+ style = context.resolve_style(component)
26
+ if isinstance(component, Heading):
27
+ return Style(font_weight=700, font_size=token(HEADING_SIZES.get(component.level, "--rk-font-md"))).merge(style)
28
+ return style
29
+
30
+
31
+ class TextDataRenderer:
32
+ """
33
+ Write text components as one-cell rows on the report information sheet.
34
+ """
35
+
36
+ def render(self, component, context, engine):
37
+ """
38
+ Append the text to the information sheet.
39
+ """
40
+ engine.information_sheet().append([(cell_value(component_text(component)), Style(font_weight=700) if isinstance(component, Heading) else Style(), None)])
@@ -0,0 +1,130 @@
1
+ import re
2
+ from functools import cache
3
+ from typing import NamedTuple
4
+
5
+ from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
6
+
7
+ from ...styles.style import Style
8
+ from ...styles.tokens import token
9
+ from .exceptions import ExcelExportError
10
+
11
+
12
+ DEFAULT_FONT = "Arial"
13
+ VERTICAL = {"top": "top", "middle": "center", "bottom": "bottom"}
14
+
15
+
16
+ class CellFormat(NamedTuple):
17
+ """
18
+ Hold the openpyxl style objects for one cell.
19
+ """
20
+
21
+ font: Font
22
+ fill: PatternFill | None
23
+ alignment: Alignment
24
+ border: Border
25
+
26
+ def apply(self, cell):
27
+ """
28
+ Apply the format to a worksheet cell.
29
+ """
30
+ cell.font, cell.alignment, cell.border = self.font, self.alignment, self.border
31
+ if self.fill:
32
+ cell.fill = self.fill
33
+
34
+
35
+ @cache
36
+ def get_format(style, direction):
37
+ """
38
+ Convert a ReportKit Style into openpyxl objects; cached because reports reuse a few styles many times.
39
+ """
40
+ return CellFormat(get_font(style), get_fill(style.background_color), get_alignment(style, direction), get_border(style))
41
+
42
+
43
+ def get_font(style):
44
+ """
45
+ Build the font from the typography properties.
46
+ """
47
+ family = (style.font_family or DEFAULT_FONT).split(",")[0].strip(" '\"")
48
+ size = points(style.font_size or token("--rk-font-md"))
49
+ return Font(name=family, size=size, bold=is_bold(style.font_weight), italic=style.font_style == "italic", color=get_color(style.color))
50
+
51
+
52
+ def get_fill(color):
53
+ """
54
+ Build a solid fill for a background color.
55
+ """
56
+ return PatternFill("solid", fgColor=get_color(color)) if color else None
57
+
58
+
59
+ def get_alignment(style, direction):
60
+ """
61
+ Build the alignment, resolving start/end against the sheet direction.
62
+ """
63
+ horizontal = get_horizontal(style.text_align, direction)
64
+ return Alignment(horizontal=horizontal, vertical=VERTICAL.get(style.vertical_align, "center"), wrap_text=True, indent=1 if horizontal in ("left", "right") else 0)
65
+
66
+
67
+ def get_horizontal(align, direction):
68
+ """
69
+ Map CSS text-align to Excel horizontal alignment.
70
+ """
71
+ sides = {"start": "right", "end": "left"} if direction == "rtl" else {"start": "left", "end": "right"}
72
+ return sides.get(align, align if align in ("left", "right", "center", "justify") else None)
73
+
74
+
75
+ def get_border(style):
76
+ """
77
+ Build the border from the shorthand border properties.
78
+ """
79
+ whole = f"{style.border_width or 1}px {style.border_style or 'solid'} {style.border_color}" if style.border_color else None
80
+ sides = [get_side(side or whole) for side in (style.border_left, style.border_right, style.border_top, style.border_bottom)]
81
+ return Border(left=sides[0], right=sides[1], top=sides[2], bottom=sides[3])
82
+
83
+
84
+ def get_side(value):
85
+ """
86
+ Convert a CSS border such as "1px solid #dddddd" into an Excel side.
87
+ """
88
+ if not value:
89
+ return Side()
90
+ width, line, color = (value.split() + ["", "", ""])[:3]
91
+ if line == "none":
92
+ return Side()
93
+ weight = float(re.sub(r"[^\d.]", "", width) or 1)
94
+ kind = "dashed" if line == "dashed" else "dotted" if line == "dotted" else "double" if line == "double" else "thick" if weight >= 3 else "medium" if weight >= 2 else "thin"
95
+ return Side(style=kind, color=get_color(color) if color else None)
96
+
97
+
98
+ def get_color(color):
99
+ """
100
+ Convert a #rgb or #rrggbb color into an Excel ARGB color.
101
+ """
102
+ if not color:
103
+ return None
104
+ match = re.fullmatch(r"#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})", color.strip())
105
+ if not match:
106
+ raise ExcelExportError(f"Excel export supports #rgb and #rrggbb colors only, got {color!r}.")
107
+ digits = match.group(1) if len(match.group(1)) == 6 else "".join(character * 2 for character in match.group(1))
108
+ return "FF" + digits.upper()
109
+
110
+
111
+ def pixels(size):
112
+ """
113
+ Convert a CSS size (number of px, "12px" or "9pt") into pixels.
114
+ """
115
+ text = str(size)
116
+ return float(re.sub(r"[^\d.]", "", text)) * (4 / 3 if text.endswith("pt") else 1)
117
+
118
+
119
+ def points(size):
120
+ """
121
+ Convert a CSS size into Excel points.
122
+ """
123
+ return round(pixels(size) * 0.75, 1)
124
+
125
+
126
+ def is_bold(weight):
127
+ """
128
+ Return whether a CSS font weight is bold.
129
+ """
130
+ return weight == "bold" or (str(weight).isdigit() and int(weight) >= 600)
@@ -0,0 +1,5 @@
1
+ from .cells import cell_value, is_formula_like
2
+ from .components import component_text
3
+ from .formats import date_format, number_format
4
+
5
+ __all__ = ["cell_value", "component_text", "date_format", "is_formula_like", "number_format"]
@@ -0,0 +1,60 @@
1
+ import math
2
+ from datetime import date, datetime
3
+ from decimal import Decimal
4
+
5
+ from ..exceptions import ExcelExportError
6
+ from .numbers import number_value
7
+
8
+ EXCEL_MAX_TEXT = 32767
9
+ FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
10
+
11
+
12
+ def cell_value(value, decimal_policy="error"):
13
+ """
14
+ Convert a prepared report value into a value Excel stores natively, without changing it.
15
+ """
16
+ if value is None or isinstance(value, bool):
17
+ return value
18
+ if isinstance(value, str):
19
+ return text_value(value)
20
+ if isinstance(value, (int, Decimal)):
21
+ return number_value(Decimal(value), value, decimal_policy)
22
+ if isinstance(value, float):
23
+ return float_value(value)
24
+ if isinstance(value, (date, datetime)):
25
+ return date_value(value)
26
+ raise ExcelExportError(f"Unsupported value type for Excel export: {type(value).__name__}.")
27
+
28
+
29
+ def float_value(value):
30
+ """
31
+ Accept finite floats only.
32
+ """
33
+ if not math.isfinite(value):
34
+ raise ExcelExportError(f"Non-finite number cannot be written to Excel: {value}.")
35
+ return value
36
+
37
+
38
+ def date_value(value):
39
+ """
40
+ Accept naive dates and datetimes; Excel has no time zones.
41
+ """
42
+ if isinstance(value, datetime) and value.tzinfo is not None:
43
+ raise ExcelExportError(f"Excel cannot store time zones; convert {value} to a naive datetime first.")
44
+ return value
45
+
46
+
47
+ def text_value(value):
48
+ """
49
+ Accept text within Excel's cell limit.
50
+ """
51
+ if len(value) > EXCEL_MAX_TEXT:
52
+ raise ExcelExportError(f"Text longer than {EXCEL_MAX_TEXT} characters cannot be written to one Excel cell.")
53
+ return value
54
+
55
+
56
+ def is_formula_like(value):
57
+ """
58
+ Return whether text would be read as a formula by Excel or spreadsheet tools.
59
+ """
60
+ return isinstance(value, str) and value.startswith(FORMULA_PREFIXES)
@@ -0,0 +1,16 @@
1
+ from ....components.information import KeyValue
2
+ from ....components.typography import Heading, RichText, Text
3
+ from ..exceptions import ExcelExportError
4
+
5
+
6
+ def component_text(component):
7
+ """
8
+ Return the text of a component placed inside a table cell.
9
+ """
10
+ if isinstance(component, (Text, Heading)):
11
+ return component.value
12
+ if isinstance(component, RichText):
13
+ return "".join(span.value for span in component.spans)
14
+ if isinstance(component, KeyValue):
15
+ return f"{component.label}: {'' if component.value is None else component.value}"
16
+ raise ExcelExportError(f"{type(component).__name__} cannot be shown inside an Excel table cell.")
@@ -0,0 +1,31 @@
1
+ import re
2
+
3
+ from ..exceptions import ExcelExportError
4
+
5
+ DATE_TOKENS = {"%Y": "yyyy", "%y": "yy", "%m": "mm", "%d": "dd", "%H": "hh", "%I": "hh", "%M": "mm", "%S": "ss", "%p": "AM/PM", "%b": "mmm", "%B": "mmmm", "%a": "ddd", "%A": "dddd", "%%": "%"}
6
+
7
+
8
+ def number_format(column):
9
+ """
10
+ Map a TableColumn format to an Excel number format, or None for plain text.
11
+ """
12
+ if column is None or column.format in (None, "text"):
13
+ return None
14
+ decimals = "0." + "0" * column.decimals if column.decimals else "0"
15
+ if column.format == "number":
16
+ return f"#,##{decimals}"
17
+ if column.format == "currency":
18
+ return f'#,##{decimals} "{column.currency}"' if column.currency else f"#,##{decimals}"
19
+ if column.format == "percent":
20
+ return f"{decimals}%"
21
+ return date_format(column.date_format or ("%Y-%m-%d %H:%M" if column.format == "datetime" else "%Y-%m-%d"))
22
+
23
+
24
+ def date_format(pattern):
25
+ """
26
+ Translate a strftime pattern into an Excel date format.
27
+ """
28
+ unknown = set(re.findall(r"%.", pattern)) - DATE_TOKENS.keys()
29
+ if unknown:
30
+ raise ExcelExportError(f"Date format directives {sorted(unknown)} have no Excel equivalent.")
31
+ return re.sub(r"%.", lambda match: DATE_TOKENS[match.group()], pattern)
@@ -0,0 +1,19 @@
1
+ from decimal import Decimal
2
+
3
+ from ..exceptions import ExcelExportError
4
+
5
+ EXCEL_DIGITS = 15
6
+ EXCEL_MAX_NUMBER = Decimal("9.99999999999999E+307")
7
+
8
+
9
+ def number_value(number, original, decimal_policy):
10
+ """
11
+ Keep numbers Excel can store exactly (15 significant digits); otherwise follow the explicit decimal policy.
12
+ """
13
+ if not number.is_finite():
14
+ raise ExcelExportError(f"Non-finite number cannot be written to Excel: {original}.")
15
+ if len(number.normalize().as_tuple().digits) <= EXCEL_DIGITS and abs(number) <= EXCEL_MAX_NUMBER:
16
+ return original if isinstance(original, int) else float(number)
17
+ if decimal_policy == "text":
18
+ return str(original)
19
+ raise ExcelExportError(f"{original} has more than {EXCEL_DIGITS} significant digits, which Excel cannot store exactly; pass decimal_policy='text' to write it as text.")
@@ -0,0 +1,5 @@
1
+ from .data import DataEngine
2
+ from .formatted import FormattedEngine
3
+ from .workbook import ExcelWorkbook
4
+
5
+ __all__ = ["DataEngine", "ExcelWorkbook", "FormattedEngine"]
@@ -0,0 +1,48 @@
1
+ from ..renderers import DATA_RENDERERS
2
+ from ..values import cell_value
3
+ from ..worksheet import DataSheet
4
+
5
+
6
+ class DataEngine:
7
+ """
8
+ Write analysis-ready sheets: report information rows, then one typed sheet per table, append-only for streaming.
9
+ """
10
+
11
+ def __init__(self, workbook, context):
12
+ """
13
+ Prepare lazy sheet creation.
14
+ """
15
+ self.workbook, self.direction, self.options, self.information, self.tables = workbook, context.direction, workbook.options, None, 0
16
+
17
+ def write(self, document, context):
18
+ """
19
+ Render the document.
20
+ """
21
+ self.render(document, context)
22
+
23
+ def render(self, component, context):
24
+ """
25
+ Render one component.
26
+ """
27
+ DATA_RENDERERS.get(component).render(component, context, self)
28
+
29
+ def information_sheet(self):
30
+ """
31
+ Return the sheet holding texts and key/value pairs, created on first use.
32
+ """
33
+ if self.information is None:
34
+ self.information = DataSheet(self.workbook.create_sheet(self.options.sheet_name), self.direction)
35
+ return self.information
36
+
37
+ def table_sheet(self, table):
38
+ """
39
+ Create the sheet for one table, named after its caption.
40
+ """
41
+ self.tables += 1
42
+ return DataSheet(self.workbook.create_sheet(table.header or f"Table {self.tables}"), self.direction)
43
+
44
+ def value(self, value):
45
+ """
46
+ Convert a report value for Excel using the configured decimal policy.
47
+ """
48
+ return cell_value(value, self.options.decimal_policy)
@@ -0,0 +1,63 @@
1
+ from ....components.document import Page
2
+ from ....styles.borders import edge_borders
3
+ from ..renderers import FORMATTED_RENDERERS
4
+ from ..renderers.base import Region
5
+ from ..styles import pixels
6
+ from ..values import cell_value
7
+ from ..worksheet import GRID_COLUMNS, FormattedSheet
8
+
9
+
10
+ class FormattedEngine:
11
+ """
12
+ Lay the report out on one page-wide sheet like the HTML/PDF output, with margins, outlines and print settings.
13
+ """
14
+
15
+ def __init__(self, workbook, context, document):
16
+ """
17
+ Create the report sheet sized to the first page of the document.
18
+ """
19
+ page = next(find_components(document, Page), None)
20
+ self.sheet, self.options = FormattedSheet(workbook.create_sheet(workbook.options.sheet_name), context.direction, page), workbook.options
21
+
22
+ def write(self, document, context):
23
+ """
24
+ Render the document across the whole column grid.
25
+ """
26
+ self.render(document, context, Region(1, 1, GRID_COLUMNS))
27
+ self.sheet.finish()
28
+
29
+ def render(self, component, context, region):
30
+ """
31
+ Render one component with its vertical margins, outline and background, and return the rows it used.
32
+ """
33
+ style = context.resolve_style(component)
34
+ top = self.add_gap(region.row, style.margin_top)
35
+ height = FORMATTED_RENDERERS.get(component).render(component, context, self, region.below(top))
36
+ if height and (style.background_color or edge_borders(style) != [None] * 4):
37
+ self.sheet.outline(region.row + top, region.column, region.width, height, style)
38
+ return top + height + self.add_gap(region.row + top + height, style.margin_bottom)
39
+
40
+ def add_gap(self, row, margin):
41
+ """
42
+ Turn a vertical CSS margin into an empty row of the same height.
43
+ """
44
+ if not margin or pixels(margin) < 4:
45
+ return 0
46
+ self.sheet.set_row_height(row, pixels(margin) * 0.75)
47
+ return 1
48
+
49
+ def value(self, value):
50
+ """
51
+ Convert a report value for Excel using the configured decimal policy.
52
+ """
53
+ return cell_value(value, self.options.decimal_policy)
54
+
55
+
56
+ def find_components(component, kind):
57
+ """
58
+ Yield the components of one type in the tree without touching table rows.
59
+ """
60
+ if isinstance(component, kind):
61
+ yield component
62
+ for child in getattr(component, "children", []):
63
+ yield from find_components(child, kind)
@@ -0,0 +1,27 @@
1
+ import re
2
+ from io import BytesIO
3
+ from zipfile import ZIP_DEFLATED, ZipFile
4
+
5
+ APPLY_FLAGS = re.compile(r"<xf [^>]*?xfId=\"\d+\"[^>]*?/?>")
6
+ APPLY_NAMES = ("applyNumberFormat", "applyFont", "applyFill", "applyBorder", "applyAlignment")
7
+
8
+
9
+ def with_apply_flags(xlsx):
10
+ """
11
+ Mark every cell format as applying its font, fill, border, alignment and number format: openpyxl omits these
12
+ flags and some Excel builds then ignore fills and borders.
13
+ """
14
+ source, target = ZipFile(BytesIO(xlsx)), BytesIO()
15
+ with ZipFile(target, "w", ZIP_DEFLATED) as archive:
16
+ for item in source.infolist():
17
+ data = source.read(item.filename)
18
+ archive.writestr(item, APPLY_FLAGS.sub(add_apply_flags, data.decode("utf-8")) if item.filename == "xl/styles.xml" else data)
19
+ return target.getvalue()
20
+
21
+
22
+ def add_apply_flags(match):
23
+ """
24
+ Add the apply flags that one cell format element is missing.
25
+ """
26
+ missing = " ".join(f'{flag}="1"' for flag in APPLY_NAMES if flag not in match.group(0))
27
+ return match.group(0).replace("<xf ", f"<xf {missing} ", 1) if missing else match.group(0)
@@ -0,0 +1,65 @@
1
+ from contextlib import suppress
2
+ from io import BytesIO
3
+
4
+ from openpyxl import Workbook
5
+
6
+ from ..exceptions import ExcelExportError
7
+ from ..exporter import INVALID_SHEET_NAME
8
+ from .styles import with_apply_flags
9
+
10
+
11
+ class ExcelWorkbook:
12
+ """
13
+ Own the openpyxl workbook: create it (standard or streaming), name its sheets and save it to bytes.
14
+ """
15
+
16
+ def __init__(self, options, context, title):
17
+ """
18
+ Create the workbook; streaming uses openpyxl's write-only mode.
19
+ """
20
+ self.options, self.direction, self.names = options, context.direction, set()
21
+ self.book = Workbook(write_only=options.streaming)
22
+ if not options.streaming:
23
+ self.book.remove(self.book.active)
24
+ self.book.properties.title = title or None
25
+
26
+ def create_sheet(self, name):
27
+ """
28
+ Create a worksheet with a unique valid name and the report direction.
29
+ """
30
+ worksheet = self.book.create_sheet(self.unique_name(name))
31
+ worksheet.sheet_view.rightToLeft = self.direction == "rtl"
32
+ return worksheet
33
+
34
+ def unique_name(self, name):
35
+ """
36
+ Make a derived sheet name valid and unique.
37
+ """
38
+ base = INVALID_SHEET_NAME.sub(" ", name).strip(" '")[:31] or "Sheet"
39
+ candidate, number = base, 2
40
+ while candidate.lower() in self.names:
41
+ suffix = f" ({number})"
42
+ candidate, number = base[:31 - len(suffix)] + suffix, number + 1
43
+ self.names.add(candidate.lower())
44
+ return candidate
45
+
46
+ def close(self):
47
+ """
48
+ Finish a streaming workbook's open sheets after a failed export without hiding the export error; nothing is
49
+ saved, so no partial file is produced.
50
+ """
51
+ if self.options.streaming:
52
+ for worksheet in self.book.worksheets:
53
+ with suppress(Exception):
54
+ worksheet.close()
55
+
56
+ def save(self):
57
+ """
58
+ Serialize the workbook to XLSX bytes.
59
+ """
60
+ buffer = BytesIO()
61
+ try:
62
+ self.book.save(buffer)
63
+ except (OSError, ValueError, TypeError) as error:
64
+ raise ExcelExportError(f"Could not write the XLSX file: {error}") from error
65
+ return with_apply_flags(buffer.getvalue())
@@ -0,0 +1,5 @@
1
+ from .constants import GRID_COLUMNS
2
+ from .data import DataSheet
3
+ from .formatted import FormattedSheet
4
+
5
+ __all__ = ["DataSheet", "FormattedSheet", "GRID_COLUMNS"]
@@ -0,0 +1,30 @@
1
+ from functools import cache
2
+
3
+ from openpyxl.styles import Border
4
+
5
+ from ....styles.borders import edge_borders
6
+ from ....styles.style import Style
7
+
8
+
9
+ @cache
10
+ def edge_style(style, on_left, on_right, on_top, on_bottom):
11
+ """
12
+ Return the border-only style of a covered cell in a merged block (the block sides on the cell's edges), or None.
13
+ """
14
+ left, right, top, bottom = edge_borders(style)
15
+ sides = {"border_left": left if on_left else None, "border_right": right if on_right else None, "border_top": top if on_top else None, "border_bottom": bottom if on_bottom else None}
16
+ return Style(**sides) if any(sides.values()) else None
17
+
18
+
19
+ def edge_border(cell, sides, row, column, width, height):
20
+ """
21
+ Combine a cell's own border with the outline sides that fall on the block edges.
22
+ """
23
+ left, right, top, bottom = sides
24
+ current = cell.border
25
+ return Border(
26
+ left=left if cell.column == column and left.style else current.left,
27
+ right=right if cell.column == column + width - 1 and right.style else current.right,
28
+ top=top if cell.row == row and top.style else current.top,
29
+ bottom=bottom if cell.row == row + height - 1 and bottom.style else current.bottom,
30
+ )