feat: improve Excel export styling with auto column widths, zebra striping, borders, and number formatting
This commit is contained in:
+132
-12
@@ -2,7 +2,7 @@ import csv
|
||||
from io import BytesIO, StringIO
|
||||
from typing import Any
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from ..core.time_utils import format_datetime, utc_now
|
||||
@@ -20,11 +20,77 @@ def _format_summary_echo(summary: dict[str, Any]) -> str:
|
||||
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
|
||||
|
||||
|
||||
# Styling constants for executive Excel reports
|
||||
_NAVY_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_ZEBRA_FILL = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
|
||||
_WHITE_FILL = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
|
||||
_SUMMARY_FILL = PatternFill(start_color="EFF6FF", end_color="EFF6FF", fill_type="solid")
|
||||
_TOTAL_FILL = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
|
||||
|
||||
_TITLE_FONT = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||
_META_FONT = Font(name="Calibri", size=9, italic=True, color="475569")
|
||||
_SUMMARY_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
_DATA_FONT = Font(name="Calibri", size=10, color="0F172A")
|
||||
_TOTAL_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
|
||||
_THIN_SIDE = Side(style="thin", color="CBD5E1")
|
||||
_CELL_BORDER = Border(left=_THIN_SIDE, right=_THIN_SIDE, top=_THIN_SIDE, bottom=_THIN_SIDE)
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
_TOTAL_BORDER = Border(
|
||||
left=_THIN_SIDE,
|
||||
right=_THIN_SIDE,
|
||||
top=Side(style="thin", color="94A3B8"),
|
||||
bottom=Side(style="double", color="1E3A8A"),
|
||||
)
|
||||
|
||||
|
||||
def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignment, str | None]:
|
||||
"""Determine alignment and Excel number format from column metadata and value."""
|
||||
key_lower = col_key.lower()
|
||||
lbl_lower = col_label.lower()
|
||||
|
||||
# Currency / Financial costs
|
||||
if any(k in key_lower or k in lbl_lower for k in ["cost", "value", "price", "amount", "budget", "estimate"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '"₹"#,##0.00' if isinstance(val, float) else '"₹"#,##0'
|
||||
return align, num_fmt
|
||||
|
||||
# Percentages
|
||||
if any(k in key_lower or k in lbl_lower for k in ["pct", "percent", "rate", "uptime"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '0.0"%"' if isinstance(val, (int, float)) else None
|
||||
return align, num_fmt
|
||||
|
||||
# Numeric counts / durations / minutes
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = "#,##0" if isinstance(val, int) else "#,##0.0"
|
||||
return align, num_fmt
|
||||
|
||||
# Dates, codes, status, IDs, booleans
|
||||
if any(k in key_lower or k in lbl_lower for k in ["date", "code", "no", "status", "priority", "criticality", "mode"]):
|
||||
align = Alignment(horizontal="center", vertical="center")
|
||||
return align, None
|
||||
|
||||
# Text / Names / Descriptions
|
||||
align = Alignment(horizontal="left", vertical="center")
|
||||
return align, None
|
||||
|
||||
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = report_payload["title"][:31]
|
||||
|
||||
# Explicitly show grid lines in Excel view
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
|
||||
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
|
||||
meta_text = (
|
||||
f"Generated: {format_datetime(utc_now())} IST | "
|
||||
@@ -32,40 +98,94 @@ def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
)
|
||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||
|
||||
ws.cell(row=1, column=1, value=title_text).font = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||
ws.cell(row=2, column=1, value=meta_text).font = Font(name="Calibri", size=10, color="475569")
|
||||
ws.cell(row=3, column=1, value=summary_text).font = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
# Row 1: Hospital Title
|
||||
ws.row_dimensions[1].height = 26
|
||||
c1 = ws.cell(row=1, column=1, value=title_text)
|
||||
c1.font = _TITLE_FONT
|
||||
c1.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 2: Metadata & Filters
|
||||
ws.row_dimensions[2].height = 18
|
||||
c2 = ws.cell(row=2, column=1, value=meta_text)
|
||||
c2.font = _META_FONT
|
||||
c2.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 3: Summary KPIs strip
|
||||
ws.row_dimensions[3].height = 22
|
||||
c3 = ws.cell(row=3, column=1, value=summary_text)
|
||||
c3.font = _SUMMARY_FONT
|
||||
c3.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 4: Spacer
|
||||
ws.row_dimensions[4].height = 10
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
|
||||
header_row = 5
|
||||
ws.row_dimensions[header_row].height = 26
|
||||
col_widths: list[int] = []
|
||||
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
|
||||
cell.fill = header_fill
|
||||
cell.font = header_font
|
||||
cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
cell.fill = _NAVY_HEADER_FILL
|
||||
cell.font = _HEADER_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _HEADER_BORDER
|
||||
col_widths.append(len(str(col["label"])))
|
||||
|
||||
# Freeze header panes
|
||||
ws.freeze_panes = "A6"
|
||||
|
||||
# Data rows
|
||||
last_data_row = header_row
|
||||
for r_offset, row_data in enumerate(rows):
|
||||
excel_row = header_row + 1 + r_offset
|
||||
last_data_row = excel_row
|
||||
ws.row_dimensions[excel_row].height = 20
|
||||
row_fill = _ZEBRA_FILL if r_offset % 2 == 1 else _WHITE_FILL
|
||||
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
val = row_data.get(col["key"])
|
||||
if isinstance(val, bool):
|
||||
val = "Yes" if val else "No"
|
||||
ws.cell(row=excel_row, column=c_idx, value=val)
|
||||
|
||||
cell = ws.cell(row=excel_row, column=c_idx, value=val)
|
||||
cell.fill = row_fill
|
||||
cell.font = _DATA_FONT
|
||||
cell.border = _CELL_BORDER
|
||||
|
||||
align, num_fmt = _detect_cell_format(col["key"], col["label"], val)
|
||||
cell.alignment = align
|
||||
if num_fmt and isinstance(val, (int, float)):
|
||||
cell.number_format = num_fmt
|
||||
|
||||
val_len = len(str(val)) if val is not None else 0
|
||||
if val_len > col_widths[c_idx - 1]:
|
||||
col_widths[c_idx - 1] = val_len
|
||||
|
||||
# Add native Excel AutoFilter on header row
|
||||
if columns:
|
||||
last_col_letter = get_column_letter(len(columns))
|
||||
ws.auto_filter.ref = f"A{header_row}:{last_col_letter}{last_data_row}"
|
||||
|
||||
# Total summary row at bottom
|
||||
if rows:
|
||||
summary_row = last_data_row + 1
|
||||
ws.row_dimensions[summary_row].height = 22
|
||||
for c_idx in range(1, len(columns) + 1):
|
||||
tot_cell = ws.cell(row=summary_row, column=c_idx)
|
||||
tot_cell.fill = _TOTAL_FILL
|
||||
tot_cell.border = _TOTAL_BORDER
|
||||
tot_cell.font = _TOTAL_FONT
|
||||
if c_idx == 1:
|
||||
tot_cell.value = f"Total Records: {len(rows)}"
|
||||
tot_cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
else:
|
||||
tot_cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
for c_idx, width in enumerate(col_widths, start=1):
|
||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(45, max(12, width + 3))
|
||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(50, max(14, width + 4))
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
|
||||
@@ -68,6 +68,36 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||
});
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(exportRows);
|
||||
|
||||
// Auto-fit column widths with generous padding so text/codes are never truncated
|
||||
const colWidths = visibleCols.map((col) => {
|
||||
const headerLabel =
|
||||
typeof col.columnDef.header === "string" ? col.columnDef.header : col.id;
|
||||
let maxLen = headerLabel.length;
|
||||
for (const row of rows) {
|
||||
const cellVal = formatExcelCell(row.getValue(col.id));
|
||||
const strVal = String(cellVal ?? "");
|
||||
if (strVal.length > maxLen) {
|
||||
maxLen = strVal.length;
|
||||
}
|
||||
}
|
||||
return { wch: Math.min(50, Math.max(14, maxLen + 3)) };
|
||||
});
|
||||
ws["!cols"] = colWidths;
|
||||
|
||||
// Add comfortable row heights: header row taller (26pt), data rows spacious (20pt)
|
||||
ws["!rows"] = [
|
||||
{ hpt: 26 },
|
||||
...rows.map(() => ({ hpt: 20 })),
|
||||
];
|
||||
|
||||
// Enable native Excel AutoFilter dropdowns on the header row
|
||||
const lastColLetter = XLSX.utils.encode_col(visibleCols.length - 1);
|
||||
ws["!autofilter"] = { ref: `A1:${lastColLetter}${rows.length + 1}` };
|
||||
|
||||
// Explicitly enable grid lines in Excel view
|
||||
ws["!views"] = [{ showGridLines: true }];
|
||||
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, "Data");
|
||||
XLSX.writeFile(wb, `${filename}.xlsx`);
|
||||
|
||||
Reference in New Issue
Block a user