xlsx_recalc.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python3
  2. """Recalculate a workbook's formulas headlessly with LibreOffice.
  3. openpyxl never computes formulas. This script shells out to `soffice`
  4. (LibreOffice) to open the workbook, recalculate, and re-save it, so
  5. cached formula results become available to `xlsx_read.py --data-only`
  6. and `--formulas`.
  7. Behavior:
  8. * soffice on PATH: converts the file to .xlsx in a temp dir (which
  9. recalculates all formulas) and replaces the original (or writes
  10. --out). Prints {"recalculated": true, ...} and exits 0.
  11. * soffice absent: prints {"recalculated": false, "reason": ...} with
  12. installation guidance and STILL exits 0 — callers can branch on the
  13. JSON instead of the exit code.
  14. Note: LibreOffice recalculates .xlsx on load per its default
  15. calculation settings; conversion re-saves with fresh cached values.
  16. Usage:
  17. xlsx_recalc.py book.xlsx
  18. xlsx_recalc.py book.xlsx --out recalced.xlsx
  19. xlsx_recalc.py book.xlsx --timeout 120
  20. """
  21. from __future__ import annotations
  22. import argparse
  23. import json
  24. import shutil
  25. import subprocess
  26. import sys
  27. import tempfile
  28. from pathlib import Path
  29. def count_cached(path):
  30. """Number of formula cells with a cached value present."""
  31. from openpyxl import load_workbook
  32. wb_f = load_workbook(path, data_only=False)
  33. wb_v = load_workbook(path, data_only=True)
  34. formulas = cached = 0
  35. for name in wb_f.sheetnames:
  36. ws_f, ws_v = wb_f[name], wb_v[name]
  37. for row in ws_f.iter_rows():
  38. for cell in row:
  39. if isinstance(cell.value, str) and cell.value.startswith("="):
  40. formulas += 1
  41. if ws_v[cell.coordinate].value is not None:
  42. cached += 1
  43. return formulas, cached
  44. def main(argv=None):
  45. ap = argparse.ArgumentParser(
  46. description="Recalculate .xlsx formulas headlessly via LibreOffice.")
  47. ap.add_argument("file", help="path to .xlsx file")
  48. ap.add_argument("--out", help="output path (default: replace input)")
  49. ap.add_argument("--timeout", type=int, default=180,
  50. help="seconds to wait for soffice (default 180)")
  51. args = ap.parse_args(argv)
  52. src = Path(args.file).resolve()
  53. if not src.exists():
  54. print(json.dumps({"ok": False, "error": f"no such file: {src}"}),
  55. file=sys.stderr)
  56. return 1
  57. soffice = shutil.which("soffice")
  58. if not soffice:
  59. print(json.dumps({
  60. "ok": True, "recalculated": False,
  61. "reason": "LibreOffice (soffice) not found on PATH",
  62. "guidance": "Install LibreOffice (e.g. `apt install "
  63. "libreoffice-calc` or `brew install --cask "
  64. "libreoffice`), or open the file in Excel/"
  65. "LibreOffice once and re-save it.",
  66. }, ensure_ascii=False))
  67. return 0
  68. with tempfile.TemporaryDirectory() as tmp:
  69. proc = subprocess.run(
  70. [soffice, "--headless", "--calc", "--convert-to", "xlsx:Calc "
  71. "MS Excel 2007 XML", "--outdir", tmp, str(src)],
  72. capture_output=True, text=True, encoding="utf-8",
  73. timeout=args.timeout,
  74. env={"HOME": tmp, "PATH": Path(soffice).parent.as_posix()
  75. + ":/usr/bin:/bin"}, check=False)
  76. produced = Path(tmp) / (src.stem + ".xlsx")
  77. if proc.returncode != 0 or not produced.exists():
  78. print(json.dumps({"ok": False,
  79. "error": "soffice conversion failed",
  80. "stderr": proc.stderr.strip()[-500:]}),
  81. file=sys.stderr)
  82. return 1
  83. formulas, cached = count_cached(produced)
  84. dest = Path(args.out).resolve() if args.out else src
  85. shutil.copyfile(produced, dest)
  86. print(json.dumps({
  87. "ok": True, "recalculated": True, "output": str(dest),
  88. "formula_cells": formulas, "with_cached_values": cached,
  89. }, ensure_ascii=False))
  90. return 0
  91. if __name__ == "__main__":
  92. try:
  93. sys.exit(main())
  94. except Exception as exc:
  95. print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)
  96. sys.exit(1)