Files
surveybox/surveybox/forms/ods.py
T
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

271 lines
12 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Minimaler Schreiber für OpenDocument-Tabellen (.ods, ODF 1.3), ohne zusätzliches Paket.
Ein Blatt mit Logo, Titel, Angaben und darunter der Tabelle: Kopfzeile fett mit 20 %
Grau und Autofilter, Spaltenbreiten fest. Für den Druck: Seitenvorlage mit Ausrichtung,
Rändern, "alle Spalten auf einer Seitenbreite", Fußzeile "Seite X von Y" und der
Kopfzeile der Tabelle als Wiederholungszeile.
Texte werden immer als Text geschrieben (nie als Formel); Zahlen als Zahl.
"""
from __future__ import annotations
import io
import re
import zipfile
from collections.abc import Sequence
from dataclasses import dataclass, field
from decimal import Decimal
from xml.sax.saxutils import escape, quoteattr
Cell = str | int | float | Decimal | None
MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet"
MAX_CELL = 32767
_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f￾￿]")
NS = (
'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '
'xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" '
'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" '
'xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" '
'xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" '
'xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" '
'xmlns:xlink="http://www.w3.org/1999/xlink" '
'xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" '
'xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" '
'xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" '
'office:version="1.3"'
)
CM_PER_CHAR = 0.21 # Spaltenbreite je Zeichen bei 10 pt
@dataclass
class Image:
png: bytes
width_cm: float
height_cm: float
@dataclass
class PageSetup:
landscape: bool = True
margins: tuple[float, float, float, float] = (1.0, 1.0, 2.0, 1.2) # links, rechts, oben, unten
fit_width: bool = True
footer: tuple[str, str] | None = None # Text vor Seitenzahl, zwischen Seitenzahl und Anzahl
@dataclass
class Sheet:
name: str
top: list[list[Cell]] # Zeilen über der Tabelle
header: list[Cell]
rows: list[list[Cell]]
widths: list[float] = field(default_factory=list) # in Zeichen
title_rows: set[int] = field(default_factory=set) # Indizes in `top`
image: Image | None = None
page: PageSetup = field(default_factory=PageSetup)
def _text(value: str) -> str:
return escape(_ILLEGAL.sub("", value)[:MAX_CELL])
def _paragraphs(value: str) -> str:
return "".join(f"<text:p>{_text(line)}</text:p>" for line in value.split("\n"))
def _cell(value: Cell, style: str = "", force: bool = False, inner: str = "") -> str:
attr = f' table:style-name="{style}"' if style else ""
if value is None or value == "":
if inner:
return f"<table:table-cell{attr}>{inner}</table:table-cell>"
return f"<table:table-cell{attr}/>" if (style and force) else "<table:table-cell/>"
if isinstance(value, bool):
value = str(value)
if isinstance(value, int | float | Decimal):
return (f'<table:table-cell{attr} office:value-type="float" office:value="{value}">'
f"<text:p>{value}</text:p>{inner}</table:table-cell>")
return (f'<table:table-cell{attr} office:value-type="string">'
f"{inner}{_paragraphs(str(value))}</table:table-cell>")
def column_name(index: int) -> str:
name = ""
index += 1
while index:
index, rest = divmod(index - 1, 26)
name = chr(65 + rest) + name
return name
def _sheet_name(name: str) -> str:
cleaned = re.sub(r"[\[\]*?:/\\'.]", " ", name).strip()[:31]
return cleaned or "Sheet1"
def _content(sheet: Sheet) -> str:
columns = max([len(sheet.header), *(len(r) for r in sheet.rows)], default=1)
widths = list(sheet.widths) + [10.0] * (columns - len(sheet.widths))
styles = "".join(
f'<style:style style:name="co{i}" style:family="table-column">'
f'<style:table-column-properties fo:break-before="auto" '
f'style:column-width="{w * CM_PER_CHAR:.2f}cm"/></style:style>'
for i, w in enumerate(widths[:columns])
)
styles += (
'<style:style style:name="ta1" style:family="table" style:master-page-name="Surveybox">'
'<style:table-properties table:display="true"/></style:style>'
'<style:style style:name="ro1" style:family="table-row">'
'<style:table-row-properties style:use-optimal-row-height="true"/></style:style>'
'<style:style style:name="roTitle" style:family="table-row">'
'<style:table-row-properties style:row-height="0.8cm"/></style:style>'
'<style:style style:name="ceHead" style:family="table-cell">'
'<style:table-cell-properties fo:background-color="#cccccc" fo:wrap-option="wrap" '
'style:vertical-align="top"/><style:text-properties fo:font-weight="bold"/>'
"</style:style>"
'<style:style style:name="ceTitle" style:family="table-cell">'
'<style:text-properties fo:font-size="14pt" fo:font-weight="bold"/></style:style>'
'<style:style style:name="ceData" style:family="table-cell">'
'<style:table-cell-properties fo:wrap-option="wrap" style:vertical-align="top"/>'
"</style:style>"
)
name = _sheet_name(sheet.name)
out = [f"<?xml version='1.0' encoding='UTF-8'?><office:document-content {NS}>",
f"<office:automatic-styles>{styles}</office:automatic-styles>",
"<office:body><office:spreadsheet>",
f"<table:table table:name={quoteattr(name)} table:style-name=\"ta1\">"]
out += [f'<table:table-column table:style-name="co{i}"/>' for i in range(columns)]
for index, row in enumerate(sheet.top):
inner = ""
if index == 0 and sheet.image is not None:
img = sheet.image
inner = (f'<draw:frame draw:name="Logo" draw:z-index="0" '
f'svg:width="{img.width_cm:.2f}cm" svg:height="{img.height_cm:.2f}cm" '
'svg:x="0cm" svg:y="0cm"><draw:image xlink:href="Pictures/logo.png" '
'xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>'
"</draw:frame>")
title = index in sheet.title_rows
cells = [_cell(v, "ceTitle" if title else "") for v in row]
if inner:
first = row[0] if row else None
cells[:1] = [_cell(first, inner=inner)]
row_style = "roTitle" if title else "ro1"
out.append(f'<table:table-row table:style-name="{row_style}">'
f"{''.join(cells) or '<table:table-cell/>'}</table:table-row>")
head = "".join(_cell(v, "ceHead", force=True) for v in sheet.header)
head += "".join(_cell(None, "ceHead", force=True)
for _ in range(columns - len(sheet.header)))
out.append('<table:table-header-rows><table:table-row table:style-name="ro1">'
f"{head}</table:table-row></table:table-header-rows>")
for row in sheet.rows:
data = "".join(_cell(v, "ceData") for v in row)
out.append(f'<table:table-row table:style-name="ro1">'
f"{data or '<table:table-cell/>'}</table:table-row>")
out.append("</table:table>")
first = len(sheet.top) + 1
last = first + max(len(sheet.rows), 1)
target = f"{quoteattr(name)[1:-1]}"
ref = f"'{target}'" if " " in target else target
out.append('<table:database-ranges><table:database-range '
'table:name="__Anonymous_Sheet_DB__0" '
f'table:target-range-address="{ref}.A{first}:{ref}.'
f'{column_name(columns - 1)}{last}" table:display-filter-buttons="true"/>'
"</table:database-ranges>")
out.append("</office:spreadsheet></office:body></office:document-content>")
return "".join(out)
def _styles(page: PageSetup) -> str:
left, right, top, bottom = page.margins
width, height = ("29.7cm", "21cm") if page.landscape else ("21cm", "29.7cm")
orientation = "landscape" if page.landscape else "portrait"
scale = ' style:scale-to-X="1" style:scale-to-Y="0" loext:scale-to-X="1" ' \
'loext:scale-to-Y="0"' if page.fit_width else ""
footer = '<style:footer style:display="false"/>'
footer_style = ""
if page.footer is not None:
before, between = page.footer
footer = ("<style:footer><style:region-center><text:p>"
f"{_text(before)}<text:page-number>1</text:page-number>{_text(between)}"
"<text:page-count>1</text:page-count></text:p></style:region-center>"
"</style:footer>")
footer_style = ('<style:footer-style><style:header-footer-properties '
'fo:min-height="0.4cm" fo:margin-top="0.2cm"/></style:footer-style>')
return (
f"<?xml version='1.0' encoding='UTF-8'?><office:document-styles {NS}>"
"<office:styles>"
'<style:default-style style:family="table-cell">'
'<style:text-properties fo:font-size="10pt"/></style:default-style>'
'<style:style style:name="Default" style:family="table-cell"/>'
"</office:styles><office:automatic-styles>"
'<style:page-layout style:name="pm1"><style:page-layout-properties '
f'fo:page-width="{width}" fo:page-height="{height}" '
f'style:print-orientation="{orientation}" fo:margin-top="{top}cm" '
f'fo:margin-bottom="{bottom}cm" fo:margin-left="{left}cm" '
f'fo:margin-right="{right}cm"{scale} '
'style:print="charts drawings objects zero-values"/>'
'<style:header-style/>'
f"{footer_style}</style:page-layout>"
"</office:automatic-styles><office:master-styles>"
'<style:master-page style:name="Surveybox" style:page-layout-name="pm1">'
f'<style:header style:display="false"/>{footer}</style:master-page>'
"</office:master-styles></office:document-styles>"
)
def _manifest(with_image: bool) -> str:
entries = [
("/", MIMETYPE),
("content.xml", "text/xml"),
("styles.xml", "text/xml"),
("meta.xml", "text/xml"),
]
if with_image:
entries.append(("Pictures/logo.png", "image/png"))
files = "".join(
f'<manifest:file-entry manifest:full-path="{path}"'
+ (' manifest:version="1.3"' if path == "/" else "")
+ f' manifest:media-type="{kind}"/>'
for path, kind in entries
)
return ("<?xml version='1.0' encoding='UTF-8'?><manifest:manifest "
'xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" '
f'manifest:version="1.3">{files}</manifest:manifest>')
def _meta(title: str) -> str:
return (f"<?xml version='1.0' encoding='UTF-8'?><office:document-meta {NS}>"
"<office:meta><meta:generator>Surveybox</meta:generator>"
f'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">{_text(title)}</dc:title>'
"</office:meta></office:document-meta>")
def document(sheet: Sheet, title: str = "") -> bytes:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as z:
# "mimetype" zuerst und unkomprimiert (ODF-Vorgabe)
z.writestr(zipfile.ZipInfo("mimetype"), MIMETYPE, compress_type=zipfile.ZIP_STORED)
z.writestr("content.xml", _content(sheet), compress_type=zipfile.ZIP_DEFLATED)
z.writestr("styles.xml", _styles(sheet.page), compress_type=zipfile.ZIP_DEFLATED)
z.writestr("meta.xml", _meta(title), compress_type=zipfile.ZIP_DEFLATED)
if sheet.image is not None:
z.writestr("Pictures/logo.png", sheet.image.png, compress_type=zipfile.ZIP_STORED)
z.writestr("META-INF/manifest.xml", _manifest(sheet.image is not None),
compress_type=zipfile.ZIP_DEFLATED)
return buffer.getvalue()
def widths_for(columns: Sequence[Sequence[Cell]]) -> list[float]:
"""Breite je Spalte in Zeichen: längster Inhalt (8 bis 50). Die Kopfzelle zählt
höchstens mit 25 Zeichen, sie bricht um."""
result = []
for col in columns:
lengths = [max((len(p) for p in str(v).split("\n")), default=0)
for v in col[1:] if v is not None]
if col:
lengths.append(min(len(str(col[0] or "")), 25))
result.append(float(min(max(max(lengths, default=8), 8), 50)) + 2)
return result