recalc.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """
  2. Excel Formula Recalculation Script
  3. Recalculates all formulas in an Excel file using LibreOffice
  4. """
  5. import json
  6. import os
  7. import platform
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from office.soffice import get_soffice_env
  12. from openpyxl import load_workbook
  13. MACRO_DIR_MACOS = "~/Library/Application Support/LibreOffice/4/user/basic/Standard"
  14. MACRO_DIR_LINUX = "~/.config/libreoffice/4/user/basic/Standard"
  15. MACRO_FILENAME = "Module1.xba"
  16. RECALCULATE_MACRO = """<?xml version="1.0" encoding="UTF-8"?>
  17. <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
  18. <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
  19. Sub RecalculateAndSave()
  20. ThisComponent.calculateAll()
  21. ThisComponent.store()
  22. ThisComponent.close(True)
  23. End Sub
  24. </script:module>"""
  25. def has_gtimeout():
  26. try:
  27. subprocess.run(
  28. ["gtimeout", "--version"], capture_output=True, timeout=1, check=False
  29. )
  30. return True
  31. except (FileNotFoundError, subprocess.TimeoutExpired):
  32. return False
  33. def setup_libreoffice_macro():
  34. macro_dir = os.path.expanduser(
  35. MACRO_DIR_MACOS if platform.system() == "Darwin" else MACRO_DIR_LINUX
  36. )
  37. macro_file = os.path.join(macro_dir, MACRO_FILENAME)
  38. if (
  39. os.path.exists(macro_file)
  40. and "RecalculateAndSave" in Path(macro_file).read_text()
  41. ):
  42. return True
  43. if not os.path.exists(macro_dir):
  44. subprocess.run(
  45. ["soffice", "--headless", "--terminate_after_init"],
  46. capture_output=True,
  47. timeout=10,
  48. env=get_soffice_env(),
  49. )
  50. os.makedirs(macro_dir, exist_ok=True)
  51. try:
  52. Path(macro_file).write_text(RECALCULATE_MACRO)
  53. return True
  54. except Exception:
  55. return False
  56. def recalc(filename, timeout=30):
  57. if not Path(filename).exists():
  58. return {"error": f"File {filename} does not exist"}
  59. abs_path = str(Path(filename).absolute())
  60. if not setup_libreoffice_macro():
  61. return {"error": "Failed to setup LibreOffice macro"}
  62. cmd = [
  63. "soffice",
  64. "--headless",
  65. "--norestore",
  66. "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application",
  67. abs_path,
  68. ]
  69. if platform.system() == "Linux":
  70. cmd = ["timeout", str(timeout)] + cmd
  71. elif platform.system() == "Darwin" and has_gtimeout():
  72. cmd = ["gtimeout", str(timeout)] + cmd
  73. result = subprocess.run(cmd, capture_output=True, text=True, env=get_soffice_env())
  74. if result.returncode != 0 and result.returncode != 124:
  75. error_msg = result.stderr or "Unknown error during recalculation"
  76. if "Module1" in error_msg or "RecalculateAndSave" not in error_msg:
  77. return {"error": "LibreOffice macro not configured properly"}
  78. return {"error": error_msg}
  79. try:
  80. wb = load_workbook(filename, data_only=True)
  81. excel_errors = [
  82. "#VALUE!",
  83. "#DIV/0!",
  84. "#REF!",
  85. "#NAME?",
  86. "#NULL!",
  87. "#NUM!",
  88. "#N/A",
  89. ]
  90. error_details = {err: [] for err in excel_errors}
  91. total_errors = 0
  92. for sheet_name in wb.sheetnames:
  93. ws = wb[sheet_name]
  94. for row in ws.iter_rows():
  95. for cell in row:
  96. if cell.value is not None and isinstance(cell.value, str):
  97. for err in excel_errors:
  98. if err in cell.value:
  99. location = f"{sheet_name}!{cell.coordinate}"
  100. error_details[err].append(location)
  101. total_errors += 1
  102. break
  103. wb.close()
  104. result = {
  105. "status": "success" if total_errors == 0 else "errors_found",
  106. "total_errors": total_errors,
  107. "error_summary": {},
  108. }
  109. for err_type, locations in error_details.items():
  110. if locations:
  111. result["error_summary"][err_type] = {
  112. "count": len(locations),
  113. "locations": locations[:20],
  114. }
  115. wb_formulas = load_workbook(filename, data_only=False)
  116. formula_count = 0
  117. for sheet_name in wb_formulas.sheetnames:
  118. ws = wb_formulas[sheet_name]
  119. for row in ws.iter_rows():
  120. for cell in row:
  121. if (
  122. cell.value
  123. and isinstance(cell.value, str)
  124. and cell.value.startswith("=")
  125. ):
  126. formula_count += 1
  127. wb_formulas.close()
  128. result["total_formulas"] = formula_count
  129. return result
  130. except Exception as e:
  131. return {"error": str(e)}
  132. def main():
  133. if len(sys.argv) < 2:
  134. print("Usage: python recalc.py <excel_file> [timeout_seconds]")
  135. print("\nRecalculates all formulas in an Excel file using LibreOffice")
  136. print("\nReturns JSON with error details:")
  137. print(" - status: 'success' or 'errors_found'")
  138. print(" - total_errors: Total number of Excel errors found")
  139. print(" - total_formulas: Number of formulas in the file")
  140. print(" - error_summary: Breakdown by error type with locations")
  141. print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A")
  142. sys.exit(1)
  143. filename = sys.argv[1]
  144. timeout = int(sys.argv[2]) if len(sys.argv) > 2 else 30
  145. result = recalc(filename, timeout)
  146. print(json.dumps(result, indent=2))
  147. if __name__ == "__main__":
  148. main()