79 lines
2.9 KiB
Python
79 lines
2.9 KiB
Python
|
|
#!/usr/bin/env python3
|
||
|
|
"""Audit an .xlsx workbook for formula errors, missing totals formulas, and narrow columns."""
|
||
|
|
import json
|
||
|
|
import sys
|
||
|
|
import unicodedata
|
||
|
|
|
||
|
|
ERROR_TOKENS = ("#REF!", "#DIV/0!", "#VALUE!", "#NAME?", "#N/A", "#NUM!", "#NULL!")
|
||
|
|
TOTAL_LABELS = ("合計", "總計", "小計", "總額", "total", "subtotal")
|
||
|
|
|
||
|
|
|
||
|
|
def display_len(s: str) -> int:
|
||
|
|
return sum(2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1 for ch in s)
|
||
|
|
|
||
|
|
|
||
|
|
def audit(path: str) -> dict:
|
||
|
|
import openpyxl
|
||
|
|
|
||
|
|
wb_f = openpyxl.load_workbook(path, data_only=False)
|
||
|
|
wb_v = openpyxl.load_workbook(path, data_only=True)
|
||
|
|
errors = []
|
||
|
|
hardcoded_totals = []
|
||
|
|
narrow_cols = []
|
||
|
|
formula_count = 0
|
||
|
|
|
||
|
|
for name in wb_f.sheetnames:
|
||
|
|
ws_f = wb_f[name]
|
||
|
|
ws_v = wb_v[name]
|
||
|
|
for row in ws_f.iter_rows():
|
||
|
|
first_text = str(row[0].value or "").strip().lower() if row else ""
|
||
|
|
is_total_row = any(lbl in first_text for lbl in TOTAL_LABELS)
|
||
|
|
for cell in row:
|
||
|
|
val = cell.value
|
||
|
|
cached = ws_v[cell.coordinate].value
|
||
|
|
for candidate in (val, cached):
|
||
|
|
if isinstance(candidate, str) and any(tok in candidate for tok in ERROR_TOKENS):
|
||
|
|
errors.append(f"{name}!{cell.coordinate}: {candidate}")
|
||
|
|
if isinstance(val, str) and val.startswith("="):
|
||
|
|
formula_count += 1
|
||
|
|
elif is_total_row and cell.column > 1 and isinstance(val, (int, float)) and val != 0:
|
||
|
|
hardcoded_totals.append(f"{name}!{cell.coordinate}={val}")
|
||
|
|
|
||
|
|
for col_cells in ws_f.columns:
|
||
|
|
col_letter = openpyxl.utils.get_column_letter(col_cells[0].column)
|
||
|
|
configured = ws_f.column_dimensions[col_letter].width
|
||
|
|
needed = 0
|
||
|
|
for c in col_cells[:200]:
|
||
|
|
v = ws_v[c.coordinate].value
|
||
|
|
if v is None:
|
||
|
|
v = c.value
|
||
|
|
if isinstance(v, str) and v.startswith("="):
|
||
|
|
continue
|
||
|
|
if v is not None:
|
||
|
|
needed = max(needed, display_len(str(v)))
|
||
|
|
if needed >= 12 and configured is not None and configured + 1 < needed:
|
||
|
|
narrow_cols.append(f"{name}!{col_letter} (width={configured:.1f}, content~{needed})")
|
||
|
|
|
||
|
|
return {
|
||
|
|
"file": path,
|
||
|
|
"sheets": wb_f.sheetnames,
|
||
|
|
"formula_cells": formula_count,
|
||
|
|
"formula_errors": errors,
|
||
|
|
"hardcoded_totals": hardcoded_totals[:20],
|
||
|
|
"narrow_columns": narrow_cols[:20],
|
||
|
|
"status": "error" if errors else ("warn" if hardcoded_totals or narrow_cols else "ok"),
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> int:
|
||
|
|
if len(sys.argv) < 2:
|
||
|
|
print("Usage: audit_xlsx.py <workbook.xlsx>", file=sys.stderr)
|
||
|
|
return 2
|
||
|
|
report = audit(sys.argv[1])
|
||
|
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||
|
|
return 1 if report["status"] == "error" else 0
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
raise SystemExit(main())
|