base.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. """
  2. xlsx skill — Base Template
  3. ===========================
  4. Single source of truth for design tokens, font resolution, and style factories.
  5. All scene/engine code MUST import from here. Never hardcode colors, fonts, or styles.
  6. Usage:
  7. from templates.base import *
  8. # To switch palette based on user prompt (call BEFORE creating styles):
  9. use_palette("帮我做一个温暖的销售月报") # Chinese prompt example
  10. # → All color tokens and style factories now use 'warm' palette.
  11. # Or manually:
  12. use_palette_explicit("warm")
  13. """
  14. import platform
  15. from openpyxl.styles import PatternFill, Font, Border, Side, Alignment
  16. from copy import copy
  17. # ============================================================
  18. # §1 Font Resolution (cross-platform fallback chain)
  19. # ============================================================
  20. def _resolve_font(candidates: list) -> str:
  21. """Return the first font name likely available on this OS."""
  22. system = platform.system()
  23. _platform_hints = {
  24. "Darwin": {"Noto Sans SC", "Noto Sans CJK SC", "Source Han Sans SC"},
  25. "Windows": {"Noto Sans SC", "Noto Sans SC", "Noto Serif SC"},
  26. "Linux": {"Noto Sans CJK SC", "WenQuanYi Micro Hei", "Source Han Sans SC"},
  27. }
  28. available = _platform_hints.get(system, set())
  29. for name in candidates:
  30. if name in available:
  31. return name
  32. return candidates[0]
  33. # CJK sans-serif fallback chain
  34. CJK_BODY_CHAIN = [
  35. "Noto Sans SC", # Free (OFL), bundled, cross-platform
  36. "Noto Sans CJK SC", # Linux / Android
  37. "Source Han Sans SC", # Adobe cross-platform (OFL)
  38. "WenQuanYi Micro Hei", # Linux fallback (GPL)
  39. ]
  40. # Latin serif (for formal reports)
  41. LATIN_BODY_CHAIN = [
  42. "FreeSerif",
  43. "serif",
  44. ]
  45. FONT_CJK = _resolve_font(CJK_BODY_CHAIN)
  46. FONT_LATIN = _resolve_font(LATIN_BODY_CHAIN)
  47. # Primary font — CJK font covers ASCII too
  48. FONT_NAME = FONT_CJK
  49. # Bold strategy: heavy-stroke fonts should NOT be bolded
  50. _HEAVY_FONTS = {
  51. "Noto Sans SC", "Noto Sans CJK SC",
  52. "Source Han Sans SC", "WenQuanYi Micro Hei",
  53. }
  54. HEADER_BOLD = FONT_NAME not in _HEAVY_FONTS
  55. # ============================================================
  56. # §2 Color Tokens (Three-Color Rule)
  57. # ============================================================
  58. # --- Primary (deep blue — professional default) ---
  59. PRIMARY = "1B2A4A"
  60. PRIMARY_LIGHT = "D6E4F0"
  61. SECONDARY = PRIMARY_LIGHT # derived from primary
  62. # --- Accent (semantic, on-demand) ---
  63. ACCENT_POSITIVE = "1B7D46" # growth, done, pass (deep green)
  64. ACCENT_NEGATIVE = "C0392B" # decline, overdue (deep red)
  65. ACCENT_WARNING = "D4820A" # at-risk, watch (deep amber)
  66. # --- Neutral (warm gray) ---
  67. NEUTRAL_900 = "37352F" # body text
  68. NEUTRAL_600 = "8C8A84" # caption, secondary text
  69. NEUTRAL_200 = "E9E9E8" # borders, dividers
  70. NEUTRAL_100 = "F7F7F5" # alternating row fill (odd)
  71. NEUTRAL_50 = "FAFAF9" # ultra-light bg (optional)
  72. NEUTRAL_0 = "FFFFFF" # white (even rows)
  73. # --- Header text color (overridable by palette) ---
  74. HEADER_TEXT = "FFFFFF"
  75. # --- Chart palette (max 5 colors) ---
  76. CHART_COLORS = [PRIMARY, ACCENT_POSITIVE, ACCENT_WARNING, ACCENT_NEGATIVE, NEUTRAL_600]
  77. # --- Conditional formatting fills ---
  78. CF_POSITIVE_FILL = PatternFill(bgColor="E8F5E9")
  79. CF_POSITIVE_FONT = Font(color=ACCENT_POSITIVE)
  80. CF_NEGATIVE_FILL = PatternFill(bgColor="FDEDEC")
  81. CF_NEGATIVE_FONT = Font(color=ACCENT_NEGATIVE)
  82. CF_WARNING_FILL = PatternFill(bgColor="FEF9E7")
  83. CF_WARNING_FONT = Font(color=ACCENT_WARNING)
  84. # --- Active style (for debugging/logging) ---
  85. _ACTIVE_STYLE = "professional"
  86. # ============================================================
  87. # §2.1 Palette Integration
  88. # ============================================================
  89. def use_palette(prompt: str):
  90. """
  91. Auto-detect style from user prompt and switch all color tokens.
  92. Call this BEFORE creating any styles/cells.
  93. Three-step matching:
  94. 1. Explicit style keywords → direct match
  95. 2. Scene/content keywords → infer style
  96. 3. No match → professional (safe default)
  97. Example:
  98. use_palette("帮我做一个温暖的销售月报") # Chinese prompt example
  99. # → 'warm' palette applied
  100. """
  101. from templates.palettes import resolve_palette_with_info
  102. palette, style = resolve_palette_with_info(prompt)
  103. _apply(palette, style)
  104. def use_palette_explicit(style: str = "professional"):
  105. """
  106. Manually select a palette by style name.
  107. Available: professional, warm, elegant, creative, muji, aesop,
  108. kinfolk, celine, bottega, chanel, bloomberg, original_blue
  109. Example:
  110. use_palette_explicit("warm")
  111. """
  112. from templates.palettes import get_palette
  113. palette = get_palette(style)
  114. _apply(palette, style)
  115. def get_active_style() -> str:
  116. """Return the currently active style name."""
  117. return _ACTIVE_STYLE
  118. def _apply(palette: dict, style: str):
  119. """Internal: apply a palette dict to all module-level color tokens."""
  120. global PRIMARY, PRIMARY_LIGHT, SECONDARY
  121. global ACCENT_POSITIVE, ACCENT_NEGATIVE, ACCENT_WARNING
  122. global NEUTRAL_900, NEUTRAL_600, NEUTRAL_200, NEUTRAL_100, NEUTRAL_50, NEUTRAL_0
  123. global CHART_COLORS, HEADER_TEXT
  124. global CF_POSITIVE_FILL, CF_POSITIVE_FONT
  125. global CF_NEGATIVE_FILL, CF_NEGATIVE_FONT
  126. global CF_WARNING_FILL, CF_WARNING_FONT
  127. global _ACTIVE_STYLE
  128. PRIMARY = palette["PRIMARY"]
  129. PRIMARY_LIGHT = palette["PRIMARY_LIGHT"]
  130. SECONDARY = palette["SECONDARY"]
  131. ACCENT_POSITIVE = palette["ACCENT_POSITIVE"]
  132. ACCENT_NEGATIVE = palette["ACCENT_NEGATIVE"]
  133. ACCENT_WARNING = palette["ACCENT_WARNING"]
  134. NEUTRAL_900 = palette["NEUTRAL_900"]
  135. NEUTRAL_600 = palette["NEUTRAL_600"]
  136. NEUTRAL_200 = palette["NEUTRAL_200"]
  137. NEUTRAL_100 = palette["NEUTRAL_100"]
  138. NEUTRAL_50 = palette["NEUTRAL_50"]
  139. NEUTRAL_0 = palette["NEUTRAL_0"]
  140. HEADER_TEXT = palette.get("HEADER_TEXT", "FFFFFF")
  141. CHART_COLORS = palette["CHART_COLORS"]
  142. # Rebuild conditional formatting fills/fonts with new accent colors
  143. CF_POSITIVE_FILL = PatternFill(bgColor=palette.get("CF_POSITIVE_BG", "E8F5E9"))
  144. CF_POSITIVE_FONT = Font(color=ACCENT_POSITIVE)
  145. CF_NEGATIVE_FILL = PatternFill(bgColor=palette.get("CF_NEGATIVE_BG", "FDEDEC"))
  146. CF_NEGATIVE_FONT = Font(color=ACCENT_NEGATIVE)
  147. CF_WARNING_FILL = PatternFill(bgColor=palette.get("CF_WARNING_BG", "FEF9E7"))
  148. CF_WARNING_FONT = Font(color=ACCENT_WARNING)
  149. _ACTIVE_STYLE = style
  150. # ============================================================
  151. # §3 Column Width Map
  152. # ============================================================
  153. COLUMN_WIDTHS = {
  154. "margin": 3, # A col whitespace
  155. "id_short": 8, # #, ID
  156. "name_cn": 16, # Chinese name (2-4 chars)
  157. "name_en": 22, # English name
  158. "description": 32, # long text
  159. "number": 14, # currency, amount
  160. "percentage": 12, # %
  161. "date": 14, # YYYY-MM-DD
  162. "status": 12, # short label
  163. }
  164. # ============================================================
  165. # §4 Number Formats
  166. # ============================================================
  167. FORMATS = {
  168. "integer": "#,##0",
  169. "decimal_1": "#,##0.0",
  170. "decimal_2": "#,##0.00",
  171. "percentage": "0.0%",
  172. "currency_cny": "¥#,##0.00",
  173. "currency_usd": "$#,##0.00",
  174. "date": "YYYY-MM-DD",
  175. }
  176. # ============================================================
  177. # §5 Style Factories
  178. # ============================================================
  179. def font_title():
  180. """16pt title font — left-aligned, no fill."""
  181. return Font(name=FONT_NAME, size=16, bold=HEADER_BOLD, color=PRIMARY)
  182. def font_header():
  183. """11pt header font — text color on primary background."""
  184. return Font(name=FONT_NAME, size=11, bold=HEADER_BOLD, color=HEADER_TEXT)
  185. def font_subheader():
  186. """11pt sub-header — primary color text."""
  187. return Font(name=FONT_NAME, size=11, bold=HEADER_BOLD, color=PRIMARY)
  188. def font_body():
  189. """11pt body text."""
  190. return Font(name=FONT_NAME, size=11, color=NEUTRAL_900)
  191. def font_caption():
  192. """9pt caption / footnote."""
  193. return Font(name=FONT_NAME, size=9, color=NEUTRAL_600)
  194. def font_kpi():
  195. """22pt big KPI number."""
  196. return Font(name=FONT_NAME, size=22, bold=HEADER_BOLD, color=PRIMARY)
  197. def font_kpi_label():
  198. """9pt KPI label."""
  199. return Font(name=FONT_NAME, size=9, color=NEUTRAL_600)
  200. def make_chart_title(text, size_pt=12, bold=True, axis=False, max_line_chars=6):
  201. """
  202. Build a chart Title with font baked into <tx><rich><defRPr>/<rPr>.
  203. Ensures WPS and Office render identical font name and size.
  204. Uses FONT_NAME and HEADER_BOLD from §1 — no hardcoded font names.
  205. Args:
  206. axis: If True, set bodyPr rot=-5400000 (rotate -90°) for Y-axis titles.
  207. max_line_chars: For axis titles, auto-insert line breaks (\n) when text
  208. exceeds this length. Breaks at parentheses boundaries.
  209. The text stays in ONE run inside ONE paragraph — this prevents
  210. WPS/Office from creating separate overlapping text boxes.
  211. Set to 0 or None to disable.
  212. Key insight: Multiple <p> paragraphs in axis titles cause WPS to render
  213. them as stacked overlapping text boxes. Instead, we use a SINGLE <r> run
  214. with \\n line breaks inside the text, which both Office and WPS render
  215. as line breaks within the same text box.
  216. """
  217. from openpyxl.chart.title import Title
  218. from openpyxl.chart.text import Text, RichText
  219. from openpyxl.drawing.text import (
  220. Paragraph, ParagraphProperties, CharacterProperties,
  221. Font as DrawingFont, RichTextProperties, RegularTextRun,
  222. LineBreak,
  223. )
  224. from copy import deepcopy
  225. import re
  226. rpr = CharacterProperties(
  227. latin=DrawingFont(typeface=FONT_NAME),
  228. ea=DrawingFont(typeface=FONT_NAME),
  229. sz=int(size_pt * 100),
  230. b=bold if HEADER_BOLD else False,
  231. )
  232. def _insert_breaks(text, max_chars):
  233. """Insert \\n before parentheses when text exceeds max_chars."""
  234. if not max_chars or len(text) <= max_chars:
  235. return text
  236. # Insert \n before '(' or '('
  237. result = re.sub(r'(?=[((])', '\n', text, count=1)
  238. return result
  239. # For axis titles, insert line breaks to prevent overlap
  240. display_text = text
  241. if axis and max_line_chars:
  242. display_text = _insert_breaks(text, max_line_chars)
  243. # Single paragraph, single run with \n inside the text.
  244. # Both Office and WPS render \n as line breaks within one text box.
  245. # Do NOT use multiple <p> paragraphs — WPS renders them as separate
  246. # overlapping text boxes on axis titles.
  247. run = RegularTextRun(rPr=deepcopy(rpr), t=display_text)
  248. inner_body = RichTextProperties(rot=-5400000) if axis else RichTextProperties()
  249. para = Paragraph(
  250. pPr=ParagraphProperties(defRPr=deepcopy(rpr)),
  251. r=[run],
  252. )
  253. rich = RichText(bodyPr=inner_body, p=[para])
  254. # Outer txPr: Office reads rotation from here for axis titles
  255. if axis:
  256. outer_body = RichTextProperties(rot=-5400000)
  257. txPr = RichText(
  258. bodyPr=outer_body,
  259. p=[Paragraph(pPr=ParagraphProperties(defRPr=deepcopy(rpr)))],
  260. )
  261. return Title(tx=Text(rich=rich), txPr=txPr)
  262. return Title(tx=Text(rich=rich))
  263. def fill_header():
  264. return PatternFill("solid", fgColor=PRIMARY)
  265. def fill_total():
  266. return PatternFill("solid", fgColor=SECONDARY)
  267. def fill_data_row(row_index: int):
  268. """Alternating row: even=white, odd=warm-white."""
  269. color = NEUTRAL_0 if row_index % 2 == 0 else NEUTRAL_100
  270. return PatternFill("solid", fgColor=color)
  271. def border_header():
  272. """Thin bottom border under header row."""
  273. return Border(bottom=Side(style="thin", color=NEUTRAL_200))
  274. def border_total():
  275. """Medium top border above totals row."""
  276. return Border(top=Side(style="medium", color=NEUTRAL_200))
  277. def align_title():
  278. return Alignment(horizontal="left", vertical="center")
  279. def align_header():
  280. return Alignment(horizontal="center", vertical="center", wrap_text=True)
  281. def align_number():
  282. return Alignment(horizontal="right", vertical="center", wrap_text=True)
  283. def align_text():
  284. return Alignment(horizontal="left", vertical="center", wrap_text=True)
  285. def align_date():
  286. return Alignment(horizontal="center", vertical="center", wrap_text=True)
  287. # ============================================================
  288. # §6 Sheet Setup Helpers
  289. # ============================================================
  290. ROW_HEIGHTS = {
  291. "margin": 15, # row 1 top whitespace
  292. "title": 32, # row 2
  293. "spacer": 8, # row 3
  294. "header": 28, # row 4
  295. "data": 22, # data rows
  296. "total": 26, # totals row
  297. }
  298. def setup_sheet(ws, title: str = None, last_col: int = None):
  299. """
  300. Apply standard sheet setup:
  301. - hide grid lines
  302. - set margin column A width
  303. - set row 1/2/3 heights
  304. - optionally write & style title at B2
  305. """
  306. ws.sheet_view.showGridLines = False
  307. ws.column_dimensions["A"].width = COLUMN_WIDTHS["margin"]
  308. ws.row_dimensions[1].height = ROW_HEIGHTS["margin"]
  309. ws.row_dimensions[2].height = ROW_HEIGHTS["title"]
  310. ws.row_dimensions[3].height = ROW_HEIGHTS["spacer"]
  311. if title and last_col:
  312. ws.merge_cells(start_row=2, start_column=2, end_row=2, end_column=last_col)
  313. cell = ws.cell(row=2, column=2, value=title)
  314. cell.font = font_title()
  315. cell.alignment = align_title()
  316. def style_header_row(ws, row_num: int, col_start: int, col_end: int):
  317. """Apply header style to a row range."""
  318. for col in range(col_start, col_end + 1):
  319. cell = ws.cell(row=row_num, column=col)
  320. cell.fill = fill_header()
  321. cell.font = font_header()
  322. cell.alignment = align_header()
  323. cell.border = border_header()
  324. ws.row_dimensions[row_num].height = ROW_HEIGHTS["header"]
  325. def style_data_row(ws, row_num: int, col_start: int, col_end: int, row_index: int):
  326. """Apply data row style (alternating fill). Enables wrap_text to prevent clipping."""
  327. fill = fill_data_row(row_index)
  328. for col in range(col_start, col_end + 1):
  329. cell = ws.cell(row=row_num, column=col)
  330. cell.fill = fill
  331. cell.font = font_body()
  332. # Preserve existing alignment but ensure wrap_text is enabled
  333. existing = cell.alignment
  334. if existing and (existing.horizontal or existing.vertical):
  335. cell.alignment = Alignment(
  336. horizontal=existing.horizontal or "left",
  337. vertical=existing.vertical or "center",
  338. wrap_text=True,
  339. )
  340. else:
  341. cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
  342. ws.row_dimensions[row_num].height = ROW_HEIGHTS["data"]
  343. def style_total_row(ws, row_num: int, col_start: int, col_end: int):
  344. """Apply totals row style."""
  345. for col in range(col_start, col_end + 1):
  346. cell = ws.cell(row=row_num, column=col)
  347. cell.fill = fill_total()
  348. cell.font = font_subheader()
  349. cell.border = border_total()
  350. ws.row_dimensions[row_num].height = ROW_HEIGHTS["total"]
  351. # ============================================================
  352. # §6.1 Chart Factory Functions
  353. # ============================================================
  354. def create_bar_chart(chart_type="col", grouping="clustered", gap_width=80,
  355. overlap=100, style=10, width=18, height=10, **kwargs):
  356. """
  357. Create a BarChart with sane defaults that prevent the "thin bar" / offset bug.
  358. Key fixes baked in:
  359. - gapWidth=80 (default 150 → bars too thin)
  360. - overlap=100 (bars fill their slot, no empty gap for line series)
  361. Returns an openpyxl BarChart ready for add_data / set_categories.
  362. """
  363. from openpyxl.chart import BarChart
  364. chart = BarChart()
  365. chart.type = chart_type
  366. chart.grouping = grouping
  367. chart.gapWidth = gap_width
  368. chart.overlap = overlap
  369. chart.style = style
  370. chart.width = width
  371. chart.height = height
  372. return chart
  373. def create_line_chart(style=10, width=18, height=11, **kwargs):
  374. """Create a LineChart with standard defaults."""
  375. from openpyxl.chart import LineChart
  376. chart = LineChart()
  377. chart.style = style
  378. chart.width = width
  379. chart.height = height
  380. return chart
  381. def create_pie_chart(style=10, width=14, height=10, **kwargs):
  382. """Create a PieChart with standard defaults."""
  383. from openpyxl.chart import PieChart
  384. chart = PieChart()
  385. chart.style = style
  386. chart.width = width
  387. chart.height = height
  388. return chart
  389. def setup_chart_titles(chart, title=None, y_title=None, x_title=None,
  390. title_size=12, axis_size=10):
  391. """
  392. Set chart title and axis titles using make_chart_title() for
  393. cross-platform font consistency (Office + WPS).
  394. This is the ONLY correct way to set chart titles. Never do:
  395. chart.title = "some string" # ← WRONG
  396. chart.y_axis.title = "some string" # ← WRONG
  397. Args:
  398. chart: openpyxl chart object
  399. title: main chart title (optional)
  400. y_title: Y-axis title (optional, auto-rotated -90°)
  401. x_title: X-axis title (optional)
  402. title_size: font size for main title (default 12)
  403. axis_size: font size for axis titles (default 10)
  404. """
  405. if title is not None:
  406. chart.title = make_chart_title(title, size_pt=title_size, bold=True)
  407. if y_title is not None:
  408. chart.y_axis.title = make_chart_title(y_title, size_pt=axis_size, bold=False, axis=True)
  409. if x_title is not None:
  410. chart.x_axis.title = make_chart_title(x_title, size_pt=axis_size, bold=False)
  411. def apply_chart_colors(chart, colors=None):
  412. """
  413. Apply palette colors to all series in a chart.
  414. Call AFTER add_data().
  415. Args:
  416. chart: openpyxl chart object (BarChart, LineChart, etc.)
  417. colors: list of hex color strings (default: CHART_COLORS)
  418. """
  419. if colors is None:
  420. colors = CHART_COLORS
  421. for i, series in enumerate(chart.series):
  422. color_hex = colors[i % len(colors)]
  423. series.graphicalProperties.solidFill = color_hex
  424. # For line charts, also set line color
  425. if hasattr(series.graphicalProperties, 'line') and series.graphicalProperties.line is not None:
  426. series.graphicalProperties.line.solidFill = color_hex
  427. def apply_pie_colors(chart, count, colors=None):
  428. """
  429. Apply palette colors to pie chart data points.
  430. Call AFTER add_data().
  431. Args:
  432. chart: openpyxl PieChart
  433. count: number of data points (slices)
  434. colors: list of hex color strings (default: CHART_COLORS)
  435. """
  436. from openpyxl.chart.series import DataPoint
  437. if colors is None:
  438. colors = CHART_COLORS
  439. for idx in range(count):
  440. pt = DataPoint(idx=idx)
  441. pt.graphicalProperties.solidFill = colors[idx % len(colors)]
  442. chart.series[0].data_points.append(pt)
  443. # ============================================================
  444. # §7 Utility Functions
  445. # ============================================================
  446. def normalize_cell_value(value):
  447. """Normalize cell values: convert invisible whitespace variants to None."""
  448. if value is None:
  449. return None
  450. if isinstance(value, str):
  451. stripped = value.strip().replace("\xa0", "").replace("\u200b", "")
  452. if stripped == "":
  453. return None
  454. return value
  455. def copy_style(source_cell, target_cell):
  456. """Copy all styling from source to target cell."""
  457. target_cell.font = copy(source_cell.font)
  458. target_cell.fill = copy(source_cell.fill)
  459. target_cell.border = copy(source_cell.border)
  460. target_cell.alignment = copy(source_cell.alignment)
  461. target_cell.number_format = source_cell.number_format
  462. def auto_fit_row_heights(ws, header_row=None, data_start_row=None, data_end_row=None,
  463. base_height=22, line_height=16, font_size=11, min_height=22):
  464. """
  465. Auto-fit row heights based on cell content and column width.
  466. Prevents text from being clipped when wrap_text causes multi-line display.
  467. Call AFTER auto_fit_columns() (needs final column widths to calculate wrapping).
  468. Args:
  469. ws: worksheet
  470. header_row: header row number (auto-detected if None)
  471. data_start_row: first data row (auto-detected as header_row + 1 if None)
  472. data_end_row: last data row (auto-detected as ws.max_row if None)
  473. base_height: base row height for single-line content (default 22)
  474. line_height: additional height per extra line (default 16)
  475. font_size: font size in pt for estimation (default 11)
  476. min_height: minimum row height (default 22)
  477. """
  478. import unicodedata
  479. import math
  480. def _display_width(text):
  481. """Estimate display width: CJK chars count as ~1.7, others as 1."""
  482. if text is None:
  483. return 0
  484. s = str(text)
  485. w = 0
  486. for ch in s:
  487. if unicodedata.east_asian_width(ch) in ('W', 'F'):
  488. w += 1.7
  489. else:
  490. w += 1
  491. return w
  492. def _estimate_lines(text, col_width):
  493. """Estimate how many lines a cell value needs given column width."""
  494. if text is None:
  495. return 1
  496. s = str(text)
  497. # Count explicit line breaks
  498. lines = s.split('\n')
  499. total_lines = 0
  500. # Available char width ≈ col_width * 0.9 (accounting for cell padding)
  501. avail_chars = max(1, col_width * 0.9)
  502. for line in lines:
  503. line_w = _display_width(line)
  504. if line_w <= avail_chars:
  505. total_lines += 1
  506. else:
  507. total_lines += math.ceil(line_w / avail_chars)
  508. return max(1, total_lines)
  509. # Auto-detect header row
  510. if header_row is None:
  511. for row in range(1, ws.max_row + 1):
  512. val = ws.cell(row=row, column=2).value
  513. if val is not None:
  514. header_row = row
  515. break
  516. if header_row is None:
  517. return
  518. if data_start_row is None:
  519. data_start_row = header_row + 1
  520. if data_end_row is None:
  521. data_end_row = ws.max_row
  522. # Get column widths
  523. col_widths = {}
  524. for col in range(1, ws.max_column + 1):
  525. col_letter = ws.cell(row=1, column=col).column_letter
  526. dim = ws.column_dimensions.get(col_letter)
  527. if dim and dim.width:
  528. col_widths[col] = dim.width
  529. else:
  530. col_widths[col] = 11 # openpyxl default
  531. # Adjust header row height
  532. max_header_lines = 1
  533. for col in range(2, ws.max_column + 1):
  534. cell = ws.cell(row=header_row, column=col)
  535. if cell.value and (cell.alignment and cell.alignment.wrap_text):
  536. lines = _estimate_lines(cell.value, col_widths.get(col, 11))
  537. max_header_lines = max(max_header_lines, lines)
  538. if max_header_lines > 1:
  539. header_height = base_height + (max_header_lines - 1) * line_height
  540. ws.row_dimensions[header_row].height = max(ROW_HEIGHTS["header"], header_height)
  541. # Adjust data rows
  542. for row_num in range(data_start_row, data_end_row + 1):
  543. max_lines = 1
  544. for col in range(2, ws.max_column + 1):
  545. cell = ws.cell(row=row_num, column=col)
  546. if cell.value is None:
  547. continue
  548. # Check if cell has wrap_text enabled
  549. has_wrap = (cell.alignment and cell.alignment.wrap_text)
  550. # Also check if content has explicit newlines
  551. has_newlines = isinstance(cell.value, str) and '\n' in cell.value
  552. if has_wrap or has_newlines:
  553. lines = _estimate_lines(cell.value, col_widths.get(col, 11))
  554. max_lines = max(max_lines, lines)
  555. if max_lines > 1:
  556. needed_height = base_height + (max_lines - 1) * line_height
  557. ws.row_dimensions[row_num].height = max(min_height, needed_height)
  558. else:
  559. # Keep at least min_height (don't shrink below base)
  560. current = ws.row_dimensions[row_num].height
  561. if current is None or current < min_height:
  562. ws.row_dimensions[row_num].height = min_height
  563. def auto_fit_columns(ws, min_width=8, max_width=28, header_row=None, data_start_row=None):
  564. """
  565. Auto-fit column widths based on DATA content (not header).
  566. Headers that exceed the computed width get wrap_text=True instead of stretching the column.
  567. Args:
  568. ws: worksheet
  569. min_width: minimum column width (default 8)
  570. max_width: maximum column width (default 28)
  571. header_row: row number of the header (auto-detected if None)
  572. data_start_row: first data row (auto-detected as header_row + 1 if None)
  573. """
  574. import unicodedata
  575. def _display_width(text):
  576. """Estimate display width: CJK chars count as ~1.7, others as 1."""
  577. if text is None:
  578. return 0
  579. s = str(text)
  580. w = 0
  581. for ch in s:
  582. if unicodedata.east_asian_width(ch) in ('W', 'F'):
  583. w += 1.7
  584. else:
  585. w += 1
  586. return w
  587. # Auto-detect header row: first row with data starting from column B
  588. if header_row is None:
  589. for row in range(1, ws.max_row + 1):
  590. val = ws.cell(row=row, column=2).value
  591. if val is not None:
  592. header_row = row
  593. break
  594. if header_row is None:
  595. return
  596. if data_start_row is None:
  597. data_start_row = header_row + 1
  598. for col_cells in ws.iter_cols(min_col=1, max_col=ws.max_column, min_row=data_start_row, max_row=ws.max_row):
  599. if not col_cells:
  600. continue
  601. col_letter = col_cells[0].column_letter
  602. # Skip margin column A
  603. if col_letter == 'A':
  604. continue
  605. # Width based on data content only
  606. max_data_w = max((_display_width(c.value) for c in col_cells), default=0)
  607. width = min(max_width, max(min_width, max_data_w + 2))
  608. ws.column_dimensions[col_letter].width = width
  609. # If header text is wider than computed column width, wrap it
  610. header_cell = ws.cell(row=header_row, column=col_cells[0].column)
  611. header_w = _display_width(header_cell.value)
  612. if header_w > width:
  613. current_align = header_cell.alignment
  614. header_cell.alignment = Alignment(
  615. horizontal=current_align.horizontal or "center",
  616. vertical=current_align.vertical or "center",
  617. wrap_text=True,
  618. )