50 lines
5.3 KiB
Python
50 lines
5.3 KiB
Python
"""Minimal XLSX writer for administrative exports without a runtime dependency."""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
from io import BytesIO
|
|
from xml.sax.saxutils import escape
|
|
from zipfile import ZIP_DEFLATED, ZipFile
|
|
|
|
|
|
def _cell(column: int, row: int, value: object, *, header: bool = False, display_timezone: timezone = timezone.utc) -> str:
|
|
name = ""
|
|
number = column
|
|
while number:
|
|
number, remainder = divmod(number - 1, 26)
|
|
name = chr(65 + remainder) + name
|
|
reference = f"{name}{row}"
|
|
style = ' s="1"' if header else ''
|
|
if isinstance(value, datetime):
|
|
timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(display_timezone)
|
|
serial = (timestamp.replace(tzinfo=None) - datetime(1899, 12, 30)).total_seconds() / 86400
|
|
return f'<c r="{reference}" s="2"><v>{serial:.10f}</v></c>'
|
|
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
return f'<c r="{reference}"{style}><v>{value}</v></c>'
|
|
return f'<c r="{reference}" t="inlineStr"{style}><is><t>{escape(str(value or ""))}</t></is></c>'
|
|
|
|
|
|
def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]], display_timezone: timezone = timezone.utc) -> bytes:
|
|
"""Build a workbook with dates converted to its user-facing time zone."""
|
|
sheet_rows = [
|
|
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True, display_timezone=display_timezone) for index, value in enumerate(headers, 1)) + '</row>'
|
|
]
|
|
for row_number, row in enumerate(rows, 2):
|
|
sheet_rows.append('<row r="%d">%s</row>' % (row_number, ''.join(
|
|
_cell(index, value_row, value, display_timezone=display_timezone) for index, value in enumerate(row, 1) for value_row in (row_number,)
|
|
)))
|
|
widths = ''.join(f'<col min="{index}" max="{index}" width="{min(max(max([len(header)] + [len(str(row[index - 1] or "")) for row in rows]) + 2, 14), 48)}" customWidth="1"/>' for index, header in enumerate(headers, 1))
|
|
sheet = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
|
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
|
'<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
|
|
f'<cols>{widths}</cols><sheetData>{"".join(sheet_rows)}</sheetData><autoFilter ref="A1:{chr(64 + len(headers))}{len(rows) + 1}"/></worksheet>')
|
|
buffer = BytesIO()
|
|
with ZipFile(buffer, 'w', ZIP_DEFLATED) as archive:
|
|
archive.writestr('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>')
|
|
archive.writestr('_rels/.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')
|
|
archive.writestr('xl/workbook.xml', f'<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="{escape(sheet_name)}" sheetId="1" r:id="rId1"/></sheets></workbook>')
|
|
archive.writestr('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
|
|
archive.writestr('xl/styles.xml', '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="dd.mm.yyyy hh:mm"/></numFmts><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><color rgb="FFFFFFFF"/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FF9A542E"/><bgColor indexed="64"/></patternFill></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellXfs count="3"><xf fontId="0" fillId="0" borderId="0"/><xf fontId="1" fillId="1" borderId="0" applyFont="1" applyFill="1"/><xf fontId="0" fillId="0" borderId="0" numFmtId="164" applyNumberFormat="1"/></cellXfs></styleSheet>')
|
|
archive.writestr('xl/worksheets/sheet1.xml', sheet)
|
|
return buffer.getvalue()
|