xlsx.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. #!/usr/bin/env python3
  2. """
  3. xlsx.py — Unified Excel Quality Assurance & Manipulation Tool
  4. Commands:
  5. recalc <xlsx> [timeout] Recalculate formulas via LibreOffice + error scan
  6. audit <xlsx> Formula error + zero-value + implicit array detection
  7. scan <xlsx> Reference anomaly detection
  8. inspect <xlsx> [--pretty] Structure analysis → JSON
  9. pivot <in> <out> [options] PivotTable with optional chart
  10. chart-verify <xlsx> Verify chart data content
  11. validate <xlsx> Structural validation (forbidden funcs, schema)
  12. Usage:
  13. python3 xlsx.py <command> [args...]
  14. python3 xlsx.py --help
  15. """
  16. from __future__ import annotations
  17. import argparse
  18. import json
  19. import os
  20. import platform
  21. import re
  22. import shutil
  23. import subprocess
  24. import sys
  25. import zipfile
  26. from collections import defaultdict
  27. from pathlib import Path
  28. from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
  29. try:
  30. from openpyxl import load_workbook, Workbook
  31. from openpyxl.utils import get_column_letter, column_index_from_string
  32. from openpyxl.utils.cell import coordinate_from_string
  33. except ImportError:
  34. print("Error: openpyxl required. Install: pip install openpyxl", file=sys.stderr)
  35. sys.exit(1)
  36. # ═══════════════════════════════════════════════════════════════
  37. # Section 0: Command registry + shared constants & helpers
  38. # ═══════════════════════════════════════════════════════════════
  39. _COMMANDS: Dict[str, Callable] = {}
  40. def cmd(name: str):
  41. """Decorator that registers a function as a CLI command."""
  42. def decorator(fn: Callable) -> Callable:
  43. _COMMANDS[name] = fn
  44. return fn
  45. return decorator
  46. # --------------- constants ---------------
  47. EXCEL_ERRORS = {"#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"}
  48. # Implicit array formula patterns that work in LibreOffice but fail in MS Excel
  49. IMPLICIT_ARRAY_PATTERNS = [
  50. (re.compile(r'MATCH\s*\(\s*TRUE\s*\(\s*\)', re.IGNORECASE),
  51. "MATCH(TRUE(), ...) requires CSE in Excel. Use SUMPRODUCT or helper column."),
  52. (re.compile(r'MATCH\s*\(\s*TRUE\s*,', re.IGNORECASE),
  53. "MATCH(TRUE, ...) with comparison range requires CSE. Use SUMPRODUCT."),
  54. (re.compile(r'MATCH\s*\([^,]+[<>=!]+[^,]+,', re.IGNORECASE),
  55. "MATCH with inline comparison requires CSE. Use SUMPRODUCT or helper column."),
  56. ]
  57. FORBIDDEN_FUNCTIONS = {
  58. "FILTER", "UNIQUE", "SORT", "SORTBY", "XLOOKUP", "XMATCH",
  59. "SEQUENCE", "LET", "LAMBDA", "RANDARRAY",
  60. "ARRAYFORMULA", "QUERY", "IMPORTRANGE",
  61. }
  62. # [Fix ①] Pattern to detect valid formula content (function calls or cell references)
  63. # A real formula must contain at least one of:
  64. # - Function call: ALPHA_CHARS( e.g. SUM(, IF(, VLOOKUP(
  65. # - Cell reference: $?[A-Z]{1,3}$?\d+ e.g. A1, $B$5, $A$1:$A$10
  66. _VALID_FORMULA_PATTERN = re.compile(
  67. r'[A-Z]{2,}\s*\(' # function call (2+ uppercase letters followed by parenthesis)
  68. r'|'
  69. r'\$?[A-Z]{1,3}\$?\d+' # cell reference like A1, $B$5
  70. ,
  71. re.IGNORECASE,
  72. )
  73. # [Fix ②] Pattern to detect external file references in formulas
  74. # Matches [filename.xlsx]SheetName! or [filename.xls]SheetName! etc.
  75. _EXT_FILE_REF_PATTERN = re.compile(r"\[([^\]]+\.(xlsx?|xlsm|xlsb|csv))\]", re.IGNORECASE)
  76. # --------------- helpers ---------------
  77. def cell_ref(sheet_name: str, cell) -> str:
  78. return f"{sheet_name}!{cell.coordinate}"
  79. def is_formula(value) -> bool:
  80. return isinstance(value, str) and value.startswith("=")
  81. def parse_range(range_str: str) -> Tuple[Optional[str], int, int, int, int]:
  82. """Parse 'Sheet!A1:F100' into (sheet, min_col, min_row, max_col, max_row)."""
  83. if "!" in range_str:
  84. sheet, rng = range_str.rsplit("!", 1)
  85. sheet = sheet.strip("'\"")
  86. else:
  87. sheet = None
  88. rng = range_str
  89. parts = rng.split(":")
  90. if len(parts) == 2:
  91. c1, r1 = coordinate_from_string(parts[0])
  92. c2, r2 = coordinate_from_string(parts[1])
  93. return sheet, column_index_from_string(c1), r1, column_index_from_string(c2), r2
  94. else:
  95. c1, r1 = coordinate_from_string(parts[0])
  96. return sheet, column_index_from_string(c1), r1, column_index_from_string(c1), r1
  97. # ═══════════════════════════════════════════════════════════════
  98. # Section 1: recalc — LibreOffice recalculation + error scan
  99. # ═══════════════════════════════════════════════════════════════
  100. def _find_soffice() -> Optional[str]:
  101. """Locate soffice binary across macOS / Linux / Windows.
  102. Search order:
  103. 1. PATH (shutil.which)
  104. 2. Platform-specific well-known locations
  105. Returns the absolute path, or None if not found.
  106. """
  107. # 1. Check PATH first (works on all platforms if user configured it)
  108. found = shutil.which("soffice")
  109. if found:
  110. return found
  111. # 2. Platform-specific search
  112. system = platform.system()
  113. if system == "Darwin":
  114. candidates = [
  115. "/Applications/LibreOffice.app/Contents/MacOS/soffice",
  116. os.path.expanduser("~/Applications/LibreOffice.app/Contents/MacOS/soffice"),
  117. ]
  118. elif system == "Linux":
  119. candidates = [
  120. "/usr/bin/soffice",
  121. "/usr/local/bin/soffice",
  122. "/usr/lib/libreoffice/program/soffice",
  123. "/opt/libreoffice/program/soffice",
  124. "/snap/bin/libreoffice.soffice", # Snap package
  125. "/var/lib/flatpak/exports/bin/org.libreoffice.LibreOffice", # Flatpak
  126. ]
  127. elif system == "Windows":
  128. candidates = [
  129. r"C:\Program Files\LibreOffice\program\soffice.exe",
  130. r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
  131. ]
  132. else:
  133. candidates = []
  134. for path in candidates:
  135. if os.path.isfile(path):
  136. return path
  137. return None
  138. def _setup_libreoffice_macro() -> bool:
  139. """Setup LibreOffice macro for recalculation if not already configured."""
  140. if platform.system() == "Darwin":
  141. macro_dir = os.path.expanduser(
  142. "~/Library/Application Support/LibreOffice/4/user/basic/Standard"
  143. )
  144. else:
  145. macro_dir = os.path.expanduser(
  146. "~/.config/libreoffice/4/user/basic/Standard"
  147. )
  148. macro_file = os.path.join(macro_dir, "Module1.xba")
  149. if os.path.exists(macro_file):
  150. with open(macro_file, "r") as f:
  151. if "RecalculateAndSave" in f.read():
  152. return True
  153. if not os.path.exists(macro_dir):
  154. soffice_bin = _find_soffice()
  155. if soffice_bin:
  156. subprocess.run(
  157. [soffice_bin, "--headless", "--terminate_after_init"],
  158. capture_output=True, timeout=10,
  159. )
  160. os.makedirs(macro_dir, exist_ok=True)
  161. macro_content = '''<?xml version="1.0" encoding="UTF-8"?>
  162. <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
  163. <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
  164. Sub RecalculateAndSave()
  165. ThisComponent.calculateAll()
  166. ThisComponent.store()
  167. ThisComponent.close(True)
  168. End Sub
  169. </script:module>'''
  170. try:
  171. with open(macro_file, "w") as f:
  172. f.write(macro_content)
  173. return True
  174. except Exception:
  175. return False
  176. def _libreoffice_recalc(filename: str, timeout: int = 30) -> Dict[str, Any]:
  177. """
  178. Recalculate formulas in an Excel file via LibreOffice,
  179. then scan ALL cells for errors.
  180. Returns a dict with status, error counts, and locations.
  181. """
  182. if not Path(filename).exists():
  183. return {"error": f"File {filename} does not exist"}
  184. abs_path = str(Path(filename).absolute())
  185. if not _setup_libreoffice_macro():
  186. return {"error": "Failed to setup LibreOffice macro"}
  187. # Locate soffice binary (cross-platform)
  188. soffice_bin = _find_soffice()
  189. if not soffice_bin:
  190. return {"error": (
  191. "LibreOffice not found — you MUST install it, not substitute it. "
  192. "FORBIDDEN: using Excel / WPS / Numbers / any program already on this machine INSTEAD "
  193. "of installing LibreOffice. FORBIDDEN: deciding the download is too large to bother "
  194. "with — being large is NOT a reason to skip it. FORBIDDEN: skipping recalculation. "
  195. "REQUIRED, in order: (1) explain to the user that LibreOffice is what actually "
  196. "recalculates the formulas so errors surface; (2) tell them the package is large "
  197. "(several hundred MB) and may take a while — information for them, not a decision "
  198. "point for you; "
  199. "(3) install it NOW — PREFERRED source is the Tsinghua TUNA mirror 'https://mirrors.tuna.tsinghua.edu.cn/libreoffice/libreoffice/stable/26.8.0/': pick the subdirectory for this platform/arch (deb/x86_64, deb/aarch64, rpm/x86_64, mac/aarch64, mac/x86_64, win/x86_64, win/aarch64) and install the main package from it; if 26.8.0 is gone, use the newest version under '.../libreoffice/stable/'. Package-manager FALLBACK only if the mirror is unreachable: macOS 'brew install --cask libreoffice'; Debian/Ubuntu 'sudo apt install libreoffice-core'; Windows 'winget install TheDocumentFoundation.LibreOffice'. "
  200. "ONLY after that install has been attempted AND failed may you use another program — "
  201. "report the failure and which checks were skipped. "
  202. "No install attempt = no substitute program."
  203. )}
  204. lo_cmd: List[str] = [
  205. soffice_bin, "--headless", "--norestore",
  206. "vnd.sun.star.script:Standard.Module1.RecalculateAndSave"
  207. "?language=Basic&location=application",
  208. abs_path,
  209. ]
  210. # Wrap with a timeout binary when available
  211. if platform.system() != "Windows":
  212. timeout_bin: Optional[str] = None
  213. if platform.system() == "Linux":
  214. timeout_bin = "timeout"
  215. elif platform.system() == "Darwin":
  216. try:
  217. subprocess.run(
  218. ["gtimeout", "--version"],
  219. capture_output=True, timeout=1, check=False,
  220. )
  221. timeout_bin = "gtimeout"
  222. except (FileNotFoundError, subprocess.TimeoutExpired):
  223. pass
  224. if timeout_bin:
  225. lo_cmd = [timeout_bin, str(timeout)] + lo_cmd
  226. result = subprocess.run(lo_cmd, capture_output=True, text=True)
  227. if result.returncode != 0 and result.returncode != 124:
  228. error_msg = result.stderr or "Unknown error during recalculation"
  229. if "Module1" in error_msg or "RecalculateAndSave" not in error_msg:
  230. return {"error": "LibreOffice macro not configured properly"}
  231. else:
  232. return {"error": error_msg}
  233. # Scan recalculated file for Excel errors
  234. try:
  235. wb = load_workbook(filename, data_only=True)
  236. excel_errors_list = [
  237. "#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"
  238. ]
  239. error_details: Dict[str, List[str]] = {err: [] for err in excel_errors_list}
  240. total_errors = 0
  241. for sheet_name in wb.sheetnames:
  242. ws = wb[sheet_name]
  243. for row in ws.iter_rows():
  244. for cell in row:
  245. if cell.value is not None and isinstance(cell.value, str):
  246. for err in excel_errors_list:
  247. if err in cell.value:
  248. location = f"{sheet_name}!{cell.coordinate}"
  249. error_details[err].append(location)
  250. total_errors += 1
  251. break
  252. wb.close()
  253. out: Dict[str, Any] = {
  254. "status": "success" if total_errors == 0 else "errors_found",
  255. "total_errors": total_errors,
  256. "error_summary": {},
  257. }
  258. for err_type, locations in error_details.items():
  259. if locations:
  260. out["error_summary"][err_type] = {
  261. "count": len(locations),
  262. "locations": locations[:20],
  263. }
  264. # Count formulas for context
  265. wb_formulas = load_workbook(filename, data_only=False)
  266. formula_count = 0
  267. for sheet_name in wb_formulas.sheetnames:
  268. ws = wb_formulas[sheet_name]
  269. for row in ws.iter_rows():
  270. for cell in row:
  271. if cell.value and isinstance(cell.value, str) and cell.value.startswith("="):
  272. formula_count += 1
  273. wb_formulas.close()
  274. out["total_formulas"] = formula_count
  275. return out
  276. except Exception as e:
  277. return {"error": str(e)}
  278. @cmd("recalc")
  279. def cmd_recalc(argv: Sequence[str]) -> int:
  280. """Recalculate formulas via LibreOffice and report errors."""
  281. parser = argparse.ArgumentParser(prog="xlsx.py recalc",
  282. description="Recalculate Excel formulas via LibreOffice")
  283. parser.add_argument("file", help="Excel file path")
  284. parser.add_argument("timeout", nargs="?", type=int, default=30,
  285. help="Timeout in seconds (default: 30)")
  286. args = parser.parse_args(argv)
  287. result = _libreoffice_recalc(args.file, args.timeout)
  288. print(json.dumps(result, indent=2, ensure_ascii=False))
  289. if "error" in result:
  290. return 1
  291. return 0 if result.get("total_errors", 0) == 0 else 1
  292. # ═══════════════════════════════════════════════════════════════
  293. # Section 2: audit — Formula error + zero-value + implicit array
  294. # ═══════════════════════════════════════════════════════════════
  295. def _run_libreoffice_recalc_best_effort(filepath: str) -> None:
  296. """Attempt LibreOffice recalc (best-effort, swallow errors)."""
  297. try:
  298. _libreoffice_recalc(filepath, timeout=30)
  299. except Exception:
  300. pass
  301. @cmd("audit")
  302. def cmd_audit(argv: Sequence[str]) -> int:
  303. """Detect formula errors, zero-value formulas, and implicit array formulas."""
  304. parser = argparse.ArgumentParser(prog="xlsx.py audit",
  305. description="Formula error scan + zero-value + implicit array detection")
  306. parser.add_argument("file", help="Excel file path")
  307. args = parser.parse_args(argv)
  308. path = Path(args.file)
  309. if not path.exists():
  310. print(json.dumps({"error": f"File not found: {path}"}))
  311. return 1
  312. # Best-effort LibreOffice recalculation first
  313. _run_libreoffice_recalc_best_effort(str(path))
  314. wb_data = load_workbook(str(path), data_only=True)
  315. wb_form = load_workbook(str(path), data_only=False)
  316. errors: List[Dict[str, Any]] = []
  317. zero_values: List[Dict[str, str]] = []
  318. implicit_arrays: List[Dict[str, str]] = []
  319. total_formulas = 0
  320. for sname in wb_form.sheetnames:
  321. ws_d = wb_data[sname]
  322. ws_f = wb_form[sname]
  323. for row_d, row_f in zip(ws_d.iter_rows(), ws_f.iter_rows()):
  324. for cd, cf in zip(row_d, row_f):
  325. fval = cf.value
  326. if not is_formula(fval):
  327. continue
  328. total_formulas += 1
  329. fstr = str(fval)
  330. # Check for formula errors in calculated value
  331. dval = cd.value
  332. if dval is not None and isinstance(dval, str):
  333. for err in EXCEL_ERRORS:
  334. if err in dval:
  335. errors.append({
  336. "cell": cell_ref(sname, cd),
  337. "error": err,
  338. "formula": fstr[:120],
  339. })
  340. break
  341. # Check for zero values (potential reference errors)
  342. if isinstance(dval, (int, float)) and dval == 0:
  343. zero_values.append({
  344. "cell": cell_ref(sname, cd),
  345. "formula": fstr[:120],
  346. })
  347. # Check for implicit array formula patterns
  348. for pattern, msg in IMPLICIT_ARRAY_PATTERNS:
  349. if pattern.search(fstr):
  350. implicit_arrays.append({
  351. "cell": cell_ref(sname, cf),
  352. "formula": fstr[:120],
  353. "issue": msg,
  354. })
  355. break
  356. wb_data.close()
  357. wb_form.close()
  358. result: Dict[str, Any] = {
  359. "total_formulas": total_formulas,
  360. "error_count": len(errors),
  361. "zero_value_count": len(zero_values),
  362. "implicit_array_count": len(implicit_arrays),
  363. }
  364. if errors:
  365. result["errors"] = errors[:50]
  366. if zero_values:
  367. result["zero_values"] = zero_values[:30]
  368. if implicit_arrays:
  369. result["implicit_arrays"] = implicit_arrays[:20]
  370. print(json.dumps(result, indent=2, ensure_ascii=False))
  371. return 1 if errors else 0
  372. # ═══════════════════════════════════════════════════════════════
  373. # Section 3: scan — Reference anomaly detection
  374. # ═══════════════════════════════════════════════════════════════
  375. @cmd("scan")
  376. def cmd_scan(argv: Sequence[str]) -> int:
  377. """Detect reference anomalies in formulas."""
  378. parser = argparse.ArgumentParser(prog="xlsx.py scan",
  379. description="Reference anomaly detection")
  380. parser.add_argument("file", help="Excel file path")
  381. args = parser.parse_args(argv)
  382. path = Path(args.file)
  383. if not path.exists():
  384. print(json.dumps({"error": f"File not found: {path}"}))
  385. return 1
  386. wb = load_workbook(str(path), data_only=False)
  387. findings: List[Dict[str, str]] = []
  388. # Pre-collect max_row for every sheet (used for cross-sheet ref check)
  389. sheet_max_rows: Dict[str, int] = {}
  390. sheet_max_cols: Dict[str, int] = {}
  391. for sn in wb.sheetnames:
  392. sw = wb[sn]
  393. sheet_max_rows[sn] = sw.max_row or 1
  394. sheet_max_cols[sn] = sw.max_column or 1
  395. for sname in wb.sheetnames:
  396. ws = wb[sname]
  397. max_data_row = sheet_max_rows[sname]
  398. max_data_col = sheet_max_cols[sname]
  399. # Collect formulas by column for pattern analysis
  400. col_formulas: Dict[Tuple[str, str], List[Tuple[int, str]]] = defaultdict(list)
  401. for row in ws.iter_rows(min_row=1, max_row=max_data_row,
  402. min_col=1, max_col=max_data_col):
  403. for c in row:
  404. if not is_formula(c.value):
  405. continue
  406. fstr = str(c.value)
  407. col_letter = get_column_letter(c.column)
  408. col_formulas[(sname, col_letter)].append((c.row, fstr))
  409. # --- Out-of-range references ---
  410. # Check for cross-sheet references: SheetName!A1:A242
  411. cross_sheet = re.findall(r"([A-Za-z_]\w*?)!([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)", fstr)
  412. if cross_sheet:
  413. for tgt_sheet, c1, r1, c2, r2 in cross_sheet:
  414. tgt_rows = sheet_max_rows.get(tgt_sheet, 0)
  415. r2_int = int(r2)
  416. # Only flag if target sheet exists and range truly exceeds it
  417. if tgt_rows > 0 and r2_int > tgt_rows * 3 and r2_int > 100:
  418. findings.append({
  419. "type": "out_of_range",
  420. "cell": cell_ref(sname, c),
  421. "detail": f"Range {tgt_sheet}!{c1}{r1}:{c2}{r2} extends far beyond {tgt_sheet} data ({tgt_rows} rows)",
  422. "formula": fstr[:100],
  423. })
  424. else:
  425. # Same-sheet reference check
  426. range_refs = re.findall(r'([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)', fstr)
  427. for c1, r1, c2, r2 in range_refs:
  428. r1_int, r2_int = int(r1), int(r2)
  429. if r2_int > max_data_row * 3 and r2_int > 100:
  430. findings.append({
  431. "type": "out_of_range",
  432. "cell": cell_ref(sname, c),
  433. "detail": f"Range {c1}{r1}:{c2}{r2} extends far beyond data ({max_data_row} rows)",
  434. "formula": fstr[:100],
  435. })
  436. # --- Header row inclusion ---
  437. agg_pattern = re.compile(
  438. r'(SUM|AVERAGE|AVG|COUNT|COUNTA|MIN|MAX|SUMPRODUCT)\s*\(\s*([A-Z]{1,3})1:',
  439. re.IGNORECASE,
  440. )
  441. agg_match = agg_pattern.search(fstr)
  442. if agg_match and c.row > 1:
  443. findings.append({
  444. "type": "header_included",
  445. "cell": cell_ref(sname, c),
  446. "detail": f"{agg_match.group(1)}() starts at row 1 (header row)",
  447. "formula": fstr[:100],
  448. })
  449. # --- Insufficient aggregate range ---
  450. small_range = re.compile(
  451. r'(SUM|AVERAGE|AVG|COUNT|COUNTA)\s*\(\s*([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)\s*\)',
  452. re.IGNORECASE,
  453. )
  454. for m in small_range.finditer(fstr):
  455. func, _, r1s, _, r2s = m.groups()
  456. span = abs(int(r2s) - int(r1s)) + 1
  457. if span <= 2:
  458. findings.append({
  459. "type": "small_aggregate",
  460. "cell": cell_ref(sname, c),
  461. "detail": f"{func}() covers only {span} cell(s)",
  462. "formula": fstr[:100],
  463. })
  464. # --- Inconsistent formula patterns within same column ---
  465. for (sh, col), entries in col_formulas.items():
  466. if len(entries) < 3:
  467. continue
  468. patterns: Dict[str, List[int]] = defaultdict(list)
  469. for row_num, fstr in entries:
  470. norm = re.sub(r'(\$?[A-Z]{1,3}\$?)\d+', r'\1#', fstr)
  471. patterns[norm].append(row_num)
  472. if len(patterns) <= 1:
  473. continue
  474. dominant_pat = max(patterns, key=lambda k: len(patterns[k]))
  475. dominant_rows = patterns[dominant_pat]
  476. for pat, rows in patterns.items():
  477. if pat == dominant_pat:
  478. continue
  479. if len(rows) <= 2 and len(rows) < len(dominant_rows):
  480. for r in rows:
  481. orig = next((f for rn, f in entries if rn == r), "?")
  482. findings.append({
  483. "type": "inconsistent_pattern",
  484. "cell": f"{sh}!{col}{r}",
  485. "detail": f"Formula differs from {len(dominant_rows)} other rows in column {col}",
  486. "formula": orig[:100],
  487. })
  488. wb.close()
  489. result: Dict[str, Any] = {
  490. "total_findings": len(findings),
  491. "by_type": {},
  492. }
  493. for f in findings:
  494. t = f["type"]
  495. result["by_type"].setdefault(t, 0)
  496. result["by_type"][t] += 1
  497. if findings:
  498. result["findings"] = findings[:60]
  499. print(json.dumps(result, indent=2, ensure_ascii=False))
  500. return 1 if findings else 0
  501. # ═══════════════════════════════════════════════════════════════
  502. # Section 4: inspect — Structure analysis → JSON
  503. # ═══════════════════════════════════════════════════════════════
  504. @cmd("inspect")
  505. def cmd_inspect(argv: Sequence[str]) -> int:
  506. """Analyse Excel file structure and output JSON."""
  507. parser = argparse.ArgumentParser(prog="xlsx.py inspect",
  508. description="Analyse file structure → JSON")
  509. parser.add_argument("file", help="Excel file path")
  510. parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON")
  511. args = parser.parse_args(argv)
  512. path = Path(args.file)
  513. if not path.exists():
  514. print(json.dumps({"error": f"File not found: {path}"}))
  515. return 1
  516. wb = load_workbook(str(path), data_only=False, read_only=False)
  517. sheets_info: List[Dict[str, Any]] = []
  518. for sname in wb.sheetnames:
  519. ws = wb[sname]
  520. max_row = ws.max_row or 0
  521. max_col = ws.max_column or 0
  522. # Extract headers (first row)
  523. headers: List[Optional[str]] = []
  524. if max_row > 0 and max_col > 0:
  525. for cell in ws[1]:
  526. if cell.value is not None:
  527. headers.append(str(cell.value))
  528. else:
  529. headers.append(None)
  530. # Build data range string
  531. if max_row > 0 and max_col > 0:
  532. data_range = f"A1:{get_column_letter(max_col)}{max_row}"
  533. else:
  534. data_range = None
  535. # Count formulas and data rows
  536. formula_count = 0
  537. data_rows = 0
  538. for row in ws.iter_rows(min_row=2, max_row=max_row, max_col=max_col):
  539. has_data = False
  540. for c in row:
  541. if c.value is not None:
  542. has_data = True
  543. if is_formula(c.value):
  544. formula_count += 1
  545. if has_data:
  546. data_rows += 1
  547. # Detect charts
  548. chart_count = 0
  549. if hasattr(ws, "_charts"):
  550. chart_count = len(ws._charts)
  551. sheet_info: Dict[str, Any] = {
  552. "name": sname,
  553. "dataRange": data_range,
  554. "rows": max_row,
  555. "columns": max_col,
  556. "dataRows": data_rows,
  557. "formulaCount": formula_count,
  558. "chartCount": chart_count,
  559. "tables": [{
  560. "headers": [h for h in headers if h is not None]
  561. }] if headers and any(h is not None for h in headers) else [],
  562. }
  563. sheets_info.append(sheet_info)
  564. wb.close()
  565. output = {"sheets": sheets_info}
  566. indent = 2 if args.pretty else None
  567. print(json.dumps(output, indent=indent, ensure_ascii=False))
  568. return 0
  569. # ═══════════════════════════════════════════════════════════════
  570. # Section 5: pivot — PivotTable with optional chart
  571. # ═══════════════════════════════════════════════════════════════
  572. def _aggregate(values: List[float], method: str) -> float:
  573. """Compute aggregation on a list of numbers."""
  574. if not values:
  575. return 0.0
  576. if method == "sum":
  577. return sum(values)
  578. elif method == "count":
  579. return float(len(values))
  580. elif method == "average":
  581. return sum(values) / len(values)
  582. elif method == "max":
  583. return max(values)
  584. elif method == "min":
  585. return min(values)
  586. return sum(values)
  587. @cmd("pivot")
  588. def cmd_pivot(argv: Sequence[str]) -> int:
  589. """Create a PivotTable-like summary with optional chart using openpyxl."""
  590. parser = argparse.ArgumentParser(prog="xlsx.py pivot",
  591. description="Create PivotTable summary with optional chart")
  592. parser.add_argument("input", help="Input Excel file")
  593. parser.add_argument("output", help="Output Excel file")
  594. parser.add_argument("--source", required=True, help="Source range: 'Sheet!A1:Z100'")
  595. parser.add_argument("--values", required=True, help="Value fields: 'Revenue:sum,Units:count'")
  596. parser.add_argument("--rows", default=None, help="Row fields: 'Product,Region'")
  597. parser.add_argument("--cols", default=None, help="Column fields: 'Quarter'")
  598. parser.add_argument("--filters", default=None, help="Filter fields: 'Year'")
  599. parser.add_argument("--location", default="PivotTable!A3", help="Output location: 'Sheet!A3'")
  600. parser.add_argument("--name", default="PivotTable1", help="PivotTable name")
  601. parser.add_argument("--style", default="monochrome", choices=["monochrome", "finance"],
  602. help="Visual style theme")
  603. parser.add_argument("--chart", default=None, choices=["bar", "line", "pie"],
  604. help="Chart type (optional)")
  605. args = parser.parse_args(argv)
  606. input_path = Path(args.input)
  607. output_path = Path(args.output)
  608. if not input_path.exists():
  609. print(json.dumps({"error": f"Input file not found: {input_path}"}))
  610. return 1
  611. # Parse source range
  612. src_sheet, src_min_col, src_min_row, src_max_col, src_max_row = parse_range(args.source)
  613. # Parse location
  614. loc = parse_range(args.location)
  615. loc_sheet = loc[0]
  616. loc_start_col = loc[1]
  617. loc_start_row = loc[2]
  618. # Parse value fields
  619. value_fields: List[Tuple[str, str]] = []
  620. for vspec in args.values.split(","):
  621. vspec = vspec.strip()
  622. if ":" in vspec:
  623. fname, agg = vspec.rsplit(":", 1)
  624. agg = agg.strip().lower()
  625. if agg in ("avg", "average"):
  626. agg = "average"
  627. else:
  628. fname = vspec
  629. agg = "sum"
  630. value_fields.append((fname.strip(), agg))
  631. row_fields = [f.strip() for f in args.rows.split(",") if f.strip()] if args.rows else []
  632. col_fields = [f.strip() for f in args.cols.split(",") if f.strip()] if args.cols else []
  633. filter_fields = [f.strip() for f in args.filters.split(",") if f.strip()] if args.filters else []
  634. # Load workbook
  635. wb = load_workbook(str(input_path))
  636. if src_sheet not in wb.sheetnames:
  637. print(json.dumps({"error": f"Source sheet '{src_sheet}' not found"}))
  638. return 1
  639. ws_src = wb[src_sheet]
  640. # Read headers from first row of source
  641. headers: List[str] = []
  642. for col_idx in range(src_min_col, src_max_col + 1):
  643. val = ws_src.cell(row=src_min_row, column=col_idx).value
  644. headers.append(str(val) if val is not None else f"Col{col_idx}")
  645. # Build column index map
  646. col_map = {h: i for i, h in enumerate(headers)}
  647. # Validate field names
  648. all_fields = row_fields + col_fields + [vf[0] for vf in value_fields] + filter_fields
  649. for f in all_fields:
  650. if f not in col_map:
  651. print(json.dumps({"error": f"Field '{f}' not found. Available: {headers}"}))
  652. return 1
  653. # Read data rows
  654. data_rows: List[Dict[str, Any]] = []
  655. for row_idx in range(src_min_row + 1, src_max_row + 1):
  656. row_data: Dict[str, Any] = {}
  657. for col_idx in range(src_min_col, src_max_col + 1):
  658. h = headers[col_idx - src_min_col]
  659. row_data[h] = ws_src.cell(row=row_idx, column=col_idx).value
  660. if any(v is not None for v in row_data.values()):
  661. data_rows.append(row_data)
  662. # Aggregate data
  663. def make_key(row: Dict[str, Any], fields: List[str]) -> Tuple[str, ...]:
  664. return tuple(str(row.get(f, "")) for f in fields)
  665. group_fields = row_fields + col_fields
  666. groups: Dict[Tuple[str, ...], Dict[str, List[float]]] = defaultdict(lambda: defaultdict(list))
  667. for row in data_rows:
  668. key = make_key(row, group_fields)
  669. for vname, _ in value_fields:
  670. val = row.get(vname)
  671. if isinstance(val, (int, float)):
  672. groups[key][vname].append(float(val))
  673. # Create or get output sheet
  674. if loc_sheet and loc_sheet in wb.sheetnames:
  675. ws_out = wb[loc_sheet]
  676. elif loc_sheet:
  677. ws_out = wb.create_sheet(loc_sheet)
  678. else:
  679. ws_out = wb.create_sheet("PivotTable")
  680. # ---- Styling ----
  681. from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
  682. # --- Font resolution (mirrors templates/base.py logic) ---
  683. _platform_hints = {
  684. "Darwin": {"Noto Sans SC", "Noto Sans CJK SC"},
  685. "Windows": {"Noto Sans SC", "Noto Sans SC"},
  686. "Linux": {"Noto Sans CJK SC", "WenQuanYi Micro Hei"},
  687. }
  688. _cjk_chain = ["Noto Sans SC", "Noto Sans CJK SC",
  689. "Source Han Sans SC", "WenQuanYi Micro Hei"]
  690. _avail = _platform_hints.get(platform.system(), set())
  691. _font_name = next((f for f in _cjk_chain if f in _avail), _cjk_chain[0])
  692. _heavy = {"Noto Sans SC", "Noto Sans CJK SC",
  693. "Source Han Sans SC", "WenQuanYi Micro Hei"}
  694. _header_bold = _font_name not in _heavy
  695. if args.style == "finance":
  696. header_fill_color = "1B2A4A" # PRIMARY from design token
  697. alt_row_color = "D6E4F0" # PRIMARY_LIGHT
  698. else: # monochrome
  699. header_fill_color = "333333"
  700. alt_row_color = "F5F5F5"
  701. header_fill = PatternFill(start_color=header_fill_color,
  702. end_color=header_fill_color, fill_type="solid")
  703. header_font = Font(name=_font_name, color="FFFFFF", bold=_header_bold, size=11)
  704. data_font = Font(name=_font_name, size=11)
  705. alt_fill = PatternFill(start_color=alt_row_color,
  706. end_color=alt_row_color, fill_type="solid")
  707. border = Border(bottom=Side(style="thin", color="D0D0D0"))
  708. # Determine if cross-matrix mode (--cols provided)
  709. use_cross_matrix = len(col_fields) > 0
  710. if use_cross_matrix:
  711. # ── Cross-matrix mode: row_fields as rows, col_fields expanded as columns ──
  712. # Collect unique column dimension values
  713. col_dim_values: List[str] = []
  714. seen_col_vals: set = set()
  715. for row in data_rows:
  716. cv = str(row.get(col_fields[0], ""))
  717. if cv not in seen_col_vals:
  718. seen_col_vals.add(cv)
  719. col_dim_values.append(cv)
  720. col_dim_values.sort()
  721. # Build cross-matrix groups: key = row_fields only, sub-key = col_dim value
  722. cross_groups: Dict[Tuple[str, ...], Dict[str, Dict[str, List[float]]]] = defaultdict(
  723. lambda: defaultdict(lambda: defaultdict(list))
  724. )
  725. for row in data_rows:
  726. rkey = make_key(row, row_fields)
  727. cval = str(row.get(col_fields[0], ""))
  728. for vname, _ in value_fields:
  729. val = row.get(vname)
  730. if isinstance(val, (int, float)):
  731. cross_groups[rkey][cval][vname].append(float(val))
  732. # Build output headers: row_fields + (col_val - agg_name) for each combination
  733. out_headers: List[str] = list(row_fields)
  734. for cv in col_dim_values:
  735. for vname, agg in value_fields:
  736. if len(value_fields) == 1:
  737. out_headers.append(f"{cv}")
  738. else:
  739. out_headers.append(f"{cv} ({vname} {agg})")
  740. # Write headers
  741. r = loc_start_row
  742. for i, h in enumerate(out_headers):
  743. cell = ws_out.cell(row=r, column=loc_start_col + i, value=h)
  744. cell.fill = header_fill
  745. cell.font = header_font
  746. cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
  747. # Sort row keys
  748. sorted_row_keys = sorted(cross_groups.keys())
  749. # Write data rows
  750. for idx, rkey in enumerate(sorted_row_keys):
  751. r += 1
  752. for i, val in enumerate(rkey):
  753. cell = ws_out.cell(row=r, column=loc_start_col + i, value=val)
  754. cell.font = data_font
  755. cell.border = border
  756. if idx % 2 == 1:
  757. cell.fill = alt_fill
  758. col_offset = len(row_fields)
  759. for cv in col_dim_values:
  760. for vname, agg in value_fields:
  761. vals = cross_groups[rkey].get(cv, {}).get(vname, [])
  762. agg_result = _aggregate(vals, agg) if vals else 0
  763. cell = ws_out.cell(row=r, column=loc_start_col + col_offset,
  764. value=round(agg_result, 2))
  765. cell.font = data_font
  766. cell.border = border
  767. cell.number_format = "#,##0.00"
  768. if idx % 2 == 1:
  769. cell.fill = alt_fill
  770. col_offset += 1
  771. sorted_keys = sorted_row_keys
  772. total_data_rows_for_chart = len(sorted_row_keys)
  773. else:
  774. # ── Flat mode: no --cols, original behavior ──
  775. out_headers: List[str] = list(row_fields)
  776. for vname, agg in value_fields:
  777. out_headers.append(f"{vname} ({agg})")
  778. # Write headers
  779. r = loc_start_row
  780. for i, h in enumerate(out_headers):
  781. cell = ws_out.cell(row=r, column=loc_start_col + i, value=h)
  782. cell.fill = header_fill
  783. cell.font = header_font
  784. cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
  785. # Sort keys for consistent output
  786. sorted_keys = sorted(groups.keys())
  787. # Write data rows
  788. for idx, key in enumerate(sorted_keys):
  789. r += 1
  790. # Row fields
  791. for i, val in enumerate(key[:len(row_fields)]):
  792. cell = ws_out.cell(row=r, column=loc_start_col + i, value=val)
  793. cell.font = data_font
  794. cell.border = border
  795. if idx % 2 == 1:
  796. cell.fill = alt_fill
  797. # Value fields
  798. for i, (vname, agg) in enumerate(value_fields):
  799. vals = groups[key].get(vname, [])
  800. agg_result = _aggregate(vals, agg)
  801. col_offset = len(row_fields) + i
  802. cell = ws_out.cell(row=r, column=loc_start_col + col_offset,
  803. value=round(agg_result, 2))
  804. cell.font = data_font
  805. cell.border = border
  806. cell.number_format = "#,##0.00"
  807. if idx % 2 == 1:
  808. cell.fill = alt_fill
  809. total_data_rows_for_chart = len(sorted_keys)
  810. # Auto-adjust column widths (data-driven, headers wrap if too wide)
  811. try:
  812. from templates.base import auto_fit_columns, auto_fit_row_heights
  813. auto_fit_columns(ws_out, min_width=10, max_width=28,
  814. header_row=loc_start_row, data_start_row=loc_start_row + 1)
  815. auto_fit_row_heights(ws_out, header_row=loc_start_row, data_start_row=loc_start_row + 1)
  816. except ImportError:
  817. # Fallback: old logic
  818. for i, h in enumerate(out_headers):
  819. col_letter = get_column_letter(loc_start_col + i)
  820. ws_out.column_dimensions[col_letter].width = max(len(str(h)) + 4, 14)
  821. # Hide gridlines
  822. ws_out.sheet_view.showGridLines = False
  823. # Add chart if requested
  824. has_chart = False
  825. total_data_rows = total_data_rows_for_chart
  826. if args.chart and total_data_rows > 0:
  827. from openpyxl.chart import BarChart, LineChart, PieChart, Reference
  828. chart_type_map = {
  829. "bar": BarChart,
  830. "line": LineChart,
  831. "pie": PieChart,
  832. }
  833. ChartClass = chart_type_map.get(args.chart, BarChart)
  834. chart = ChartClass()
  835. chart.title = args.name or "PivotTable Summary"
  836. chart.style = 10
  837. data_ref = Reference(
  838. ws_out,
  839. min_col=loc_start_col + len(row_fields),
  840. min_row=loc_start_row,
  841. max_col=loc_start_col + len(out_headers) - 1,
  842. max_row=loc_start_row + total_data_rows,
  843. )
  844. cats_ref = Reference(
  845. ws_out,
  846. min_col=loc_start_col,
  847. min_row=loc_start_row + 1,
  848. max_row=loc_start_row + total_data_rows,
  849. )
  850. chart.add_data(data_ref, titles_from_data=True)
  851. chart.set_categories(cats_ref)
  852. if isinstance(chart, BarChart):
  853. chart.type = "col"
  854. # Pie chart: prevent label overlap with bestFit + leader lines
  855. if isinstance(chart, PieChart):
  856. from openpyxl.chart.label import DataLabelList
  857. chart.dataLabels = DataLabelList()
  858. chart.dataLabels.dLblPos = 'bestFit'
  859. chart.dataLabels.showLeaderLines = True
  860. chart.dataLabels.showCatName = True
  861. chart.dataLabels.showPercent = True
  862. chart.dataLabels.showVal = False
  863. chart.dataLabels.showSerName = False
  864. # Anchor with enough vertical offset to avoid chart-to-chart overlap
  865. # ~15 rows per chart height; leave 2 extra rows gap
  866. chart_row_offset = 17
  867. chart_anchor = ws_out.cell(
  868. row=loc_start_row + total_data_rows + 3,
  869. column=loc_start_col,
  870. ).coordinate
  871. ws_out.add_chart(chart, chart_anchor)
  872. has_chart = True
  873. wb.save(str(output_path))
  874. wb.close()
  875. # [Fix ③] Auto-recalc after pivot if chart was created, so chart data cache is populated
  876. if has_chart:
  877. try:
  878. _run_libreoffice_recalc_best_effort(str(output_path))
  879. except Exception:
  880. pass
  881. print(json.dumps({
  882. "status": "success",
  883. "output": str(output_path),
  884. "pivot_rows": total_data_rows,
  885. "fields": {
  886. "rows": row_fields,
  887. "columns": col_fields,
  888. "values": [f"{v}:{a}" for v, a in value_fields],
  889. "filters": filter_fields,
  890. },
  891. "chart": args.chart or "none",
  892. }, indent=2, ensure_ascii=False))
  893. return 0
  894. # ═══════════════════════════════════════════════════════════════
  895. # Section 6: chart-verify — Verify chart data content
  896. # ═══════════════════════════════════════════════════════════════
  897. def _check_charts(filepath: str) -> Tuple[List[Dict], List[Dict]]:
  898. """Core chart verification logic. Returns (ok_charts, empty_charts)."""
  899. wb = load_workbook(filepath)
  900. ok_charts: List[Dict[str, str]] = []
  901. empty_charts: List[Dict[str, str]] = []
  902. for sname in wb.sheetnames:
  903. ws = wb[sname]
  904. if not hasattr(ws, "_charts"):
  905. continue
  906. for chart in ws._charts:
  907. chart_title = "untitled"
  908. if chart.title:
  909. try:
  910. parts = []
  911. for p in chart.title.tx.rich.paragraphs:
  912. for run in p.r:
  913. if hasattr(run, 't') and run.t:
  914. parts.append(run.t)
  915. chart_title = "".join(parts) if parts else "untitled"
  916. except (AttributeError, TypeError):
  917. chart_title = "untitled"
  918. has_data = False
  919. for series in (chart.series if hasattr(chart, "series") else []):
  920. if hasattr(series, "val") and series.val:
  921. ref = series.val
  922. if hasattr(ref, "numRef") and ref.numRef:
  923. cache = ref.numRef.numCache if hasattr(ref.numRef, "numCache") else None
  924. if cache and hasattr(cache, "ptCount") and cache.ptCount and cache.ptCount > 0:
  925. has_data = True
  926. break
  927. if hasattr(ref, "numLit") and ref.numLit:
  928. has_data = True
  929. break
  930. entry = {"sheet": sname, "title": chart_title}
  931. if has_data:
  932. ok_charts.append(entry)
  933. else:
  934. empty_charts.append(entry)
  935. wb.close()
  936. return ok_charts, empty_charts
  937. @cmd("chart-verify")
  938. def cmd_chart_verify(argv: Sequence[str]) -> int:
  939. """Verify all charts have actual data content.
  940. [Fix ④] Automatically recalc first if charts appear empty, then re-check.
  941. """
  942. parser = argparse.ArgumentParser(prog="xlsx.py chart-verify",
  943. description="Verify all charts have actual data")
  944. parser.add_argument("file", help="Excel file path")
  945. parser.add_argument("--no-auto-recalc", action="store_true",
  946. help="Disable automatic recalc before checking")
  947. args = parser.parse_args(argv)
  948. path = Path(args.file)
  949. if not path.exists():
  950. print(json.dumps({"error": f"File not found: {path}"}))
  951. return 1
  952. ok_charts, empty_charts = _check_charts(str(path))
  953. # [Fix ④] If there are empty charts and auto-recalc is enabled, try recalc first
  954. if empty_charts and not args.no_auto_recalc:
  955. try:
  956. _run_libreoffice_recalc_best_effort(str(path))
  957. # Re-check after recalc
  958. ok_charts, empty_charts = _check_charts(str(path))
  959. except Exception:
  960. pass
  961. total_charts = len(ok_charts) + len(empty_charts)
  962. result: Dict[str, Any] = {
  963. "total_charts": total_charts,
  964. "charts_with_data": len(ok_charts),
  965. "empty_charts": len(empty_charts),
  966. }
  967. if empty_charts:
  968. result["empty"] = empty_charts
  969. if ok_charts:
  970. result["ok"] = ok_charts
  971. print(json.dumps(result, indent=2, ensure_ascii=False))
  972. if empty_charts:
  973. return 1
  974. if total_charts == 0:
  975. print("No charts found in workbook.", file=sys.stderr)
  976. return 0
  977. return 0
  978. # ═══════════════════════════════════════════════════════════════
  979. # Section 7: validate — Structural validation
  980. # ═══════════════════════════════════════════════════════════════
  981. @cmd("validate")
  982. def cmd_validate(argv: Sequence[str]) -> int:
  983. """Structural validation: forbidden functions, formula hygiene, schema basics."""
  984. parser = argparse.ArgumentParser(prog="xlsx.py validate",
  985. description="Structural validation (forbidden funcs, schema)")
  986. parser.add_argument("file", help="Excel file path")
  987. args = parser.parse_args(argv)
  988. path = Path(args.file)
  989. if not path.exists():
  990. print(json.dumps({"error": f"File not found: {path}"}))
  991. return 1
  992. wb = load_workbook(str(path), data_only=False)
  993. issues: List[Dict[str, str]] = []
  994. for sname in wb.sheetnames:
  995. ws = wb[sname]
  996. for row in ws.iter_rows():
  997. for c in row:
  998. if not is_formula(c.value):
  999. continue
  1000. fstr = str(c.value).upper()
  1001. # Check for forbidden functions
  1002. for func in FORBIDDEN_FUNCTIONS:
  1003. pattern = re.compile(rf'\b{func}\s*\(', re.IGNORECASE)
  1004. if pattern.search(fstr):
  1005. issues.append({
  1006. "type": "forbidden_function",
  1007. "cell": cell_ref(sname, c),
  1008. "function": func,
  1009. "detail": f"{func}() is not supported in Excel 2019 and earlier",
  1010. "formula": str(c.value)[:100],
  1011. })
  1012. # Check for text accidentally treated as formula
  1013. raw = str(c.value)
  1014. is_formula_cell = getattr(c, "data_type", None) == "f"
  1015. if (raw.startswith("=") and not is_formula_cell
  1016. and not any(ch in raw for ch in "+-*/()&,!:$")):
  1017. issues.append({
  1018. "type": "text_as_formula",
  1019. "cell": cell_ref(sname, c),
  1020. "detail": "Text starts with '=' — may be misinterpreted as formula",
  1021. "value": raw[:80],
  1022. })
  1023. # [Fix ①] Heuristic: data_type=='f' but content has no valid formula elements
  1024. if is_formula_cell and raw.startswith("="):
  1025. body = raw[1:] # strip leading =
  1026. body_stripped = body.strip()
  1027. if body_stripped.startswith('"'):
  1028. pass # starts with a quoted string, likely intentional
  1029. elif not _VALID_FORMULA_PATTERN.search(body):
  1030. issues.append({
  1031. "type": "text_as_formula",
  1032. "cell": cell_ref(sname, c),
  1033. "detail": "Cell stored as formula but contains no function calls or cell references — likely text starting with '='",
  1034. "value": raw[:80],
  1035. })
  1036. # [Fix ②] Check for external file references in formulas
  1037. if _EXT_FILE_REF_PATTERN.search(fstr):
  1038. ext_matches = _EXT_FILE_REF_PATTERN.findall(fstr)
  1039. for ext_file, _ in ext_matches:
  1040. issues.append({
  1041. "type": "external_file_ref",
  1042. "cell": cell_ref(sname, c),
  1043. "detail": f"Formula references external file: {ext_file}",
  1044. "formula": str(c.value)[:100],
  1045. })
  1046. # Check for absolute paths / local file references in .rels
  1047. try:
  1048. with zipfile.ZipFile(str(path), "r") as zf:
  1049. for name in zf.namelist():
  1050. if name.endswith(".rels"):
  1051. content = zf.read(name).decode("utf-8", errors="ignore")
  1052. if re.search(r'Target="[A-Z]:\\', content):
  1053. issues.append({
  1054. "type": "absolute_path",
  1055. "file": name,
  1056. "detail": "Absolute Windows path in .rels file — causes Excel crash",
  1057. })
  1058. if "file:///" in content.lower():
  1059. issues.append({
  1060. "type": "local_file_ref",
  1061. "file": name,
  1062. "detail": "Local file:// reference in .rels — may cause security warning",
  1063. })
  1064. except Exception:
  1065. pass # zipfile inspection is best-effort
  1066. wb.close()
  1067. by_type: Dict[str, int] = defaultdict(int)
  1068. for iss in issues:
  1069. by_type[iss["type"]] += 1
  1070. result: Dict[str, Any] = {
  1071. "status": "passed" if not issues else "failed",
  1072. "total_issues": len(issues),
  1073. "by_type": dict(by_type),
  1074. }
  1075. if issues:
  1076. result["issues"] = issues[:50]
  1077. print(json.dumps(result, indent=2, ensure_ascii=False))
  1078. return 0 if not issues else 1
  1079. # ═══════════════════════════════════════════════════════════════
  1080. # Section 8: CLI entry point
  1081. # ═══════════════════════════════════════════════════════════════
  1082. _HELP_TEXT = """\
  1083. xlsx.py — Unified Excel Quality Assurance & Manipulation Tool
  1084. Usage: python3 xlsx.py <command> [args...]
  1085. Commands:
  1086. recalc <xlsx> [timeout] Recalculate formulas via LibreOffice + error scan
  1087. audit <xlsx> Formula error + zero-value + implicit array detection
  1088. scan <xlsx> Reference anomaly detection
  1089. inspect <xlsx> [--pretty] Structure analysis → JSON
  1090. pivot <in> <out> --source ... [options] PivotTable with optional chart
  1091. chart-verify <xlsx> [--no-auto-recalc] Verify chart data content
  1092. validate <xlsx> Structural validation
  1093. Run 'python3 xlsx.py <command> --help' for command-specific options.
  1094. """
  1095. def main() -> int:
  1096. if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h"):
  1097. print(_HELP_TEXT)
  1098. return 0
  1099. command = sys.argv[1]
  1100. rest = sys.argv[2:]
  1101. handler = _COMMANDS.get(command)
  1102. if handler is None:
  1103. print(f"Unknown command: {command}\n", file=sys.stderr)
  1104. print(_HELP_TEXT, file=sys.stderr)
  1105. return 1
  1106. return handler(rest)
  1107. if __name__ == "__main__":
  1108. sys.exit(main())