ai-idea-screener / export.py
avalarku's picture
AI Use Check v2
b79e956 verified
Raw History Blame Contribute Delete
3.04 kB
"""Builds register rows as CSV or XLSX. Nothing is written to disk."""
import csv
import io
from openpyxl import Workbook
from openpyxl.styles import Alignment, Font
from .content import load_content
def columns() -> list[dict]:
return load_content()["register"]["columns"]
def _safe(value: str) -> str:
# Stop spreadsheet apps treating a cell as a formula.
return "'" + value if value[:1] in ("=", "+", "@") else value
def row_values(row: dict) -> list[str]:
return [_safe(str(row.get(c["key"], "") or "").strip()) for c in columns()]
def to_csv(rows: list[dict]) -> bytes:
content = load_content()
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow([c["label"] for c in columns()])
writer.writerows(row_values(row) for row in rows)
writer.writerow([])
writer.writerow([content["step6"]["watch_heading"]])
for item in content["step6"]["watch_for"]:
writer.writerow([item])
# UTF-8 BOM so Excel opens accented characters and dashes correctly.
return ("" + buf.getvalue()).encode("utf-8")
ACTION_COLUMNS = [("check", "AI use", 30), ("when", "When", 18), ("what", "What to do", 70),
("why", "Why", 34), ("done", "Done", 10), ("link", "Link", 30)]
def to_xlsx(rows: list[dict], actions: list[dict] | None = None) -> bytes:
"""The register rows, plus an "Action list" sheet (one row per action) when actions are given."""
content = load_content()
wb = Workbook()
if actions:
sheet = wb.active
sheet.title = content["step6"]["download_label"]
sheet.append([label for _, label, _ in ACTION_COLUMNS])
for a in actions:
sheet.append([_safe(str(a.get(key, "") or "").strip()) for key, _, _ in ACTION_COLUMNS])
for cell in sheet[1]:
cell.font = Font(bold=True)
for i, (_, _, width) in enumerate(ACTION_COLUMNS):
letter = sheet.cell(row=1, column=i + 1).column_letter
sheet.column_dimensions[letter].width = width
for cell in sheet[letter]:
cell.alignment = Alignment(wrap_text=True, vertical="top")
sheet.freeze_panes = "A2"
sheet.auto_filter.ref = sheet.dimensions
ws = wb.create_sheet("AI register")
else:
ws = wb.active
ws.title = "AI register"
ws.append([c["label"] for c in columns()])
for row in rows:
ws.append(row_values(row))
for cell in ws[1]:
cell.font = Font(bold=True)
for col_cells in ws.columns:
ws.column_dimensions[col_cells[0].column_letter].width = 36
for cell in col_cells:
cell.alignment = Alignment(wrap_text=True, vertical="top")
watch = wb.create_sheet(content["step6"]["watch_sheet"])
watch.append([content["step6"]["watch_heading"]])
watch["A1"].font = Font(bold=True)
for item in content["step6"]["watch_for"]:
watch.append([item])
watch.column_dimensions["A"].width = 70
out = io.BytesIO()
wb.save(out)
return out.getvalue()