Files
cwshed-clone/app/belki/xlsx_export.py
T

50 lines
5.1 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) -> 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(timezone.utc)
serial = (timestamp - datetime(1899, 12, 30, tzinfo=timezone.utc)).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]]) -> bytes:
"""Builds one readable XLSX worksheet with a frozen, styled header row."""
sheet_rows = [
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True) 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) 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()