#!/usr/bin/env python3 """Export a cashbook from the database as a spreadsheet (.ods / .xlsx) or CSV. The spreadsheet uses the cashbook template's layout: one sheet per month with GST and category columns, plus the summary sheet. Usage: export.py BOOK OUT.{ods,xlsx,csv} [--data DIR] """ import argparse import csv import io import os import shutil import tempfile import ledger HERE = os.path.dirname(os.path.abspath(__file__)) TEMPLATE = os.path.join(HERE, "template.ods") FORMATS = { "ods": ("application/vnd.oasis.opendocument.spreadsheet", None), "xlsx": ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Calc MS Excel 2007 XML"), "csv": ("text/csv", None), } def export_csv(conn, book): out = io.StringIO() w = csv.writer(out) w.writerow(["Date", "Month", "Reference", "Payment origin", "In", "Out", "GST type", "GST", "Net (excl GST)", "Category"]) for sheet in ledger.FY_ORDER: m = ledger.read_month(conn, book, sheet) for r in m["rows"]: w.writerow([r["date"], m["label"], r["reference"], r["origin"], f"{r['income']:.2f}" if r["income"] else "", f"{r['expense']:.2f}" if r["expense"] else "", r["gst"], f"{r['gst_in'] or r['gst_out']:.2f}", f"{r['net']:.2f}", r["category"] or "Unallocated"]) return out.getvalue().encode("utf-8-sig") # BOM so Excel reads UTF-8 def export_spreadsheet(conn, book, fmt, open_fn): """Fill a copy of the template and return its bytes. `open_fn` opens a document (office.Office.open).""" import cashbook # needs LibreOffice's Python bridge from office import prop months = {s: ledger.read_month(conn, book, s)["rows"] for s in ledger.FY_ORDER} tmp = tempfile.mkdtemp(prefix="cashbook_export_") try: path = os.path.join(tmp, "book.ods") shutil.copy(TEMPLATE, path) with open_fn(path) as doc: cashbook.write_book(doc, book["start_year"], book["opening_cents"] / 100, months) if fmt == "ods": doc.store() else: import uno path = os.path.join(tmp, f"book.{fmt}") doc.storeToURL(uno.systemPathToFileUrl(path), (prop("FilterName", FORMATS[fmt][1]),)) with open(path, "rb") as f: return f.read() finally: shutil.rmtree(tmp, ignore_errors=True) def export(conn, book, fmt, open_fn=None): if fmt not in FORMATS: raise ValueError(f"unknown format {fmt!r}; use ods, xlsx or csv") if fmt == "csv": return export_csv(conn, book) if open_fn is None: from office import open_book as open_fn return export_spreadsheet(conn, book, fmt, open_fn) def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("book", help="book name") ap.add_argument("out", help="file to write; the extension picks the format") ap.add_argument("--data", default=os.path.join(os.path.dirname(HERE), "data")) args = ap.parse_args() conn = ledger.connect(os.path.join(args.data, "cashbook.db")) fmt = os.path.splitext(args.out)[1].lstrip(".").lower() data = export(conn, ledger.get_book(conn, args.book), fmt) with open(args.out, "wb") as f: f.write(data) print(f"Wrote {args.out}") if __name__ == "__main__": main()