From 2cfd530ced7625eea86453a2f5ccd63f178542d6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 22 Jul 2026 06:33:43 +0000 Subject: [PATCH] Add cross-platform OOXML backend alongside Windows Excel COM Linux/macOS default to surgical zip edits that clear/set cells while preserving queries, styles, and other non-worksheet parts. Windows keeps the COM + add-in path. Paths remapped via XLSX_CLEAN_ROOT; pywin32 is Windows-only. Co-authored-by: Diaco Soltanpour --- AGENTS.md | 48 +++-- README.md | 35 ++- pyproject.toml | 5 +- requirements-dev.lock | 2 +- requirements.lock | 2 +- src/xlsx_clean/__main__.py | 4 + src/xlsx_clean/clean_cells.py | 259 +++++++++++++---------- src/xlsx_clean/com_backend.py | 64 ++++++ src/xlsx_clean/new_xslx.bat | 3 +- src/xlsx_clean/ooxml_backend.py | 362 ++++++++++++++++++++++++++++++++ src/xlsx_clean/paths.py | 63 ++++++ 11 files changed, 707 insertions(+), 140 deletions(-) create mode 100644 src/xlsx_clean/__main__.py create mode 100644 src/xlsx_clean/com_backend.py create mode 100644 src/xlsx_clean/ooxml_backend.py create mode 100644 src/xlsx_clean/paths.py diff --git a/AGENTS.md b/AGENTS.md index 073cc0f..f66ec95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,28 +1,37 @@ # xlsx-clean -`xlsx-clean` is a small **Windows-only** Python CLI (`src/xlsx_clean/clean_cells.py`) that -generates a new Excel QC datasheet from the most recent workbook in a configured directory, -clearing/resetting specific cells via Microsoft Excel COM automation (`pywin32`). +`xlsx-clean` is a Python CLI (`src/xlsx_clean/clean_cells.py`) that generates a new +Excel QC datasheet from the most recent workbook in a configured directory, +clearing/resetting specific cells. + +## Backends + +- **`com` (Windows default):** Microsoft Excel COM via `pywin32`. Loads add-ins listed + in `strings.txt`, edits cells, `SaveAs`, leaves Excel visible/maximized. +- **`ooxml` (Linux/macOS default):** Surgical edit of the `.xlsx` zip (worksheet XML + only). Preserves non-worksheet parts (styles, connections/Power Query definitions, + drawings, etc.). Does not calculate formulas or refresh queries. + +Select with `--backend com|ooxml`. ## Cursor Cloud specific instructions -### Platform limitation (important) -- The app is **Windows-only** and **cannot run end-to-end on this Linux VM**: - - `pywin32` has no Linux wheels, so it is intentionally **not** installed here. - - `src/xlsx_clean/clean_cells.py` imports `win32com.client` at module top level and drives - the desktop **Microsoft Excel** app via COM, plus reads `D:\OpenCloud\...` Windows paths - from `src/xlsx_clean/file_data.csv`. None of that exists on Linux. -- What **does** run on Linux: everything except the Excel COM layer, i.e. the config/data - logic (reading `strings.txt` + `file_data.csv` with `pandas`, resolving the set/ink-color - selection, and computing the new workbook filename from the `[SERIAL]` pattern). +### Platform notes +- `pywin32` has no Linux wheels and is declared as Windows-only + (`pywin32>=306; sys_platform == 'win32'`). It is intentionally **not** installed here. +- End-to-end COM automation needs Windows + desktop Excel and does not run on this VM. +- On Linux, the **ooxml** backend can clear/set cells and write a new workbook when + sample files and `XLSX_CLEAN_ROOT` point at a real tree. Without those data files, + interactive selection still works for config loading, but globbing finds no templates. ### Environment -- Dependencies are installed into a `uv`-managed virtualenv at `.venv` by the startup update - script (`uv` itself is installed via `pip install --break-system-packages uv` and lives in - `~/.local/bin`, which is on PATH for interactive shells via `~/.bashrc`). -- The install faithfully uses pinned versions from `requirements.lock`, excluding the `-e file:.` +- Dependencies are installed into a `uv`-managed virtualenv at `.venv` by the startup + update script (`uv` itself is installed via `pip install --break-system-packages uv` + and lives in `~/.local/bin`, which is on PATH for interactive shells via `~/.bashrc`). +- The install uses pinned versions from `requirements.lock`, excluding the `-e file:.` editable line and `pywin32`; the package is then installed editable with `--no-deps`. - Run Python via the venv interpreter: `.venv/bin/python`. +- Optional: `XLSX_CLEAN_ROOT` remaps `D:\OpenCloud\...` paths from `file_data.csv`. ### Lint / test / build - There is **no lint config, no test suite, and no build step** in this repo (no ruff/flake8, @@ -30,8 +39,7 @@ clearing/resetting specific cells via Microsoft Excel COM automation (`pywin32`) - `pyproject.toml` uses `hatchling` as the build backend; there is nothing to "build" for dev. ### Running / verifying -- The interactive tool (`cd src/xlsx_clean && python clean_cells.py`) needs Windows + Excel and - will fail on import here — do not expect it to run on the VM. -- To sanity-check the environment on Linux, verify imports and the package: - `.venv/bin/python -c "import pandas, beaupy; from xlsx_clean import hello; print(hello())"`. +- Interactive tool: `.venv/bin/python -m xlsx_clean.clean_cells` (defaults to `ooxml` on Linux). +- Sanity-check imports: + `.venv/bin/python -c "import pandas, beaupy; from xlsx_clean import hello; from xlsx_clean.ooxml_backend import expand_a1_range; print(hello(), expand_a1_range('A1:B2'))"`. - Note: the `uv`-created `.venv` does not include `pip`; use `uv pip ...` for package operations. diff --git a/README.md b/README.md index c9c2fc1..02d65a0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,36 @@ # xlsx-clean -Create a new xlsx file from the last file in a dir and clear specified cells. \ No newline at end of file +Create a new QC datasheet from the latest matching workbook: clear configured +cells, blank notes, write the batch serial, and save under a new `[SERIAL]` name. + +## Platforms + +| Platform | Default backend | Behavior | +|----------|-----------------|----------| +| Windows | `com` | Microsoft Excel via `pywin32`; loads add-ins from `strings.txt`; leaves Excel open | +| Linux / macOS | `ooxml` | Surgical OOXML zip edit; preserves formulas, formatting, queries/connections on disk | + +Force a backend with `--backend com` or `--backend ooxml`. + +The OOXML path does **not** refresh Power Query, evaluate formulas, or load `.xlam`/`.xla` +add-ins. Open the written file in Excel for refresh/calc. Prefer `com` on Windows when +you need add-ins and a live Excel session. + +## Config + +- `src/xlsx_clean/file_data.csv` — product dirs, filename patterns, cells to clear/set +- `src/xlsx_clean/strings.txt` — prompts + Windows add-in paths (COM only) +- `XLSX_CLEAN_ROOT` — optional root that replaces `D:\OpenCloud` in CSV paths + (example: `export XLSX_CLEAN_ROOT=/mnt/opencloud`) + +## Run + +```bash +# installed entry point +xlsx-clean + +# or module +python -m xlsx_clean.clean_cells --backend ooxml +``` + +On Windows, `src/xlsx_clean/new_xslx.bat` runs the same module entry point. diff --git a/pyproject.toml b/pyproject.toml index 0c0fbf5..1017b32 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,11 +8,14 @@ authors = [ dependencies = [ "beaupy>=3.8.2", "pandas>=2.2.2", - "pywin32>=306", + "pywin32>=306; sys_platform == 'win32'", ] readme = "README.md" requires-python = ">= 3.12" +[project.scripts] +xlsx-clean = "xlsx_clean.clean_cells:main" + [build-system] requires = ["hatchling"] build-backend = "hatchling.build" diff --git a/requirements-dev.lock b/requirements-dev.lock index 19fd574..7e7adb4 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -30,7 +30,7 @@ python-yakh==0.3.2 pytz==2024.1 # via pandas pywin32==306 - # via xlsx-clean + # via xlsx-clean; Windows-only (sys_platform == 'win32') questo==0.2.3 # via beaupy rich==13.7.1 diff --git a/requirements.lock b/requirements.lock index 19fd574..7e7adb4 100644 --- a/requirements.lock +++ b/requirements.lock @@ -30,7 +30,7 @@ python-yakh==0.3.2 pytz==2024.1 # via pandas pywin32==306 - # via xlsx-clean + # via xlsx-clean; Windows-only (sys_platform == 'win32') questo==0.2.3 # via beaupy rich==13.7.1 diff --git a/src/xlsx_clean/__main__.py b/src/xlsx_clean/__main__.py new file mode 100644 index 0000000..4898163 --- /dev/null +++ b/src/xlsx_clean/__main__.py @@ -0,0 +1,4 @@ +from xlsx_clean.clean_cells import main + +if __name__ == "__main__": + main() diff --git a/src/xlsx_clean/clean_cells.py b/src/xlsx_clean/clean_cells.py index 03c2c2c..2501724 100644 --- a/src/xlsx_clean/clean_cells.py +++ b/src/xlsx_clean/clean_cells.py @@ -1,136 +1,165 @@ -from datetime import datetime -import pathlib +"""Interactive CLI: copy latest QC workbook, clear cells, stamp serial.""" + +from __future__ import annotations + +import argparse import shutil +import sys +import tempfile +from datetime import datetime +from pathlib import Path import pandas from beaupy import prompt, select - -# from openpyxl import load_workbook from rich.console import Console -import win32com.client as win32 + +from xlsx_clean.paths import ( + default_backend, + get_opencloud_root, + package_file, + remap_opencloud_path, + resolve_backend, +) NEW_VALUE = "" -# import questionary -# load questions from text file -with open("strings.txt") as f: - content = f.readlines() -# remove whitespace characters like `\n` at the end of each line -content = [x.strip() for x in content] -q1 = content[0] -q2 = content[1] -q3 = content[2] - -path_df = pandas.read_csv("file_data.csv") -path_df["set_dir"] = [pathlib.Path(path).parent.parent for path in path_df["dir"]] -path_list = [pathlib.Path(path) for path in path_df["dir"]] -parent_path = list( - path_df.drop_duplicates(subset=["set_name"], keep="first")["set_name"] -) - -# get parent path index -console = Console() -console.print(q1) -selected_set = select(parent_path, cursor_style="cyan") - -console.print(q2) -selected_dir = select( - [ - pathlib.Path(path).stem - for path in list(path_df[path_df["set_name"] == selected_set]["dir"]) - ] -) -console.print(f"Selected: {selected_dir}") -path_ = pathlib.Path( - path_df[ - (path_df["set_name"] == selected_set) - & (path_df["dir"].str.endswith(selected_dir)) - ]["dir"].iloc[0] -) -pattern = path_df[ - (path_df["set_name"] == selected_set) & (path_df["dir"].str.endswith(selected_dir)) -]["pattern"].iloc[0] -search_pattern = pattern.replace("[SERIAL]", "*") -names = path_.glob(search_pattern) -files = [str(x) for x in names if x.is_file()] - -batch_serial = 0 -# Prompt for serial -batch_serial = prompt(q3, target_type=str) -def find_last_workbook(files): - # Sort the list of files by their names - sorted_files = sorted(files) - - # The last file will be the one at the end of the sorted list - last_file = sorted_files[-1] - - return last_file +def find_last_workbook(files: list[str]) -> str: + return sorted(files)[-1] -def get_workbook_names(files, batch_serial): +def get_workbook_names( + files: list[str], + batch_serial: str, + source_dir: Path, + pattern: str, +) -> tuple[str, Path]: last_workbook = find_last_workbook(files) - path_of_the_year = pathlib.Path(str(path_).replace("2025", str(datetime.now().year))) + path_of_the_year = Path(str(source_dir).replace("2025", str(datetime.now().year))) return last_workbook, path_of_the_year / pattern.replace( "[SERIAL]", batch_serial.split("/")[0] ) -ref_workbook_name, new_workbook_name = get_workbook_names(files, batch_serial) -# Selected Excel file -console.print(f"Selected: {pathlib.Path(ref_workbook_name).stem}") -# workbook = load_workbook(ref_workbook_name) -temp_workbook = str(pathlib.Path.cwd() / "temp_workbook.xlsx") -shutil.copyfile(ref_workbook_name, temp_workbook) +def load_config() -> tuple[list[str], pandas.DataFrame]: + strings_path = package_file("strings.txt") + with open(strings_path, encoding="utf-8") as f: + content = [line.strip() for line in f.readlines()] -# in case of this error -# AttributeError: module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9' has no attribute 'CLSIDToClassMap' -# see https://stackoverflow.com/questions/52889704 -excel = win32.gencache.EnsureDispatch("Excel.Application") -excel.Visible = True + path_df = pandas.read_csv(package_file("file_data.csv")) + root = get_opencloud_root() + path_df["dir"] = [ + str(remap_opencloud_path(path, root)) for path in path_df["dir"] + ] + return content, path_df -# Need to load the addins before opening the workbook -workbook = excel.Workbooks.Open(temp_workbook) -addin_path_1 = content[3] -excel.Workbooks.Open(addin_path_1) -addin_path_2 = content[4] -excel.Workbooks.Open(addin_path_2) -cells_to_clear = path_df[ - (path_df["set_name"] == selected_set) & (path_df["dir"].str.endswith(selected_dir)) -]["cells_to_clear"].iloc[0] -for workbook_data in cells_to_clear.split(","): - worksheet_data = workbook_data.split("!") - # worksheet = workbook[worksheet_data[0].replace("'", "")] - worksheet = workbook.Worksheets(worksheet_data[0].replace("'", "")) - # TODO: delete - # is_range = len(worksheet_data[1].split(":")) > 1 - - cell_range = worksheet.Range(worksheet_data[1]).ClearContents() -cells_to_new_value = path_df[ - (path_df["set_name"] == selected_set) & (path_df["dir"].str.endswith(selected_dir)) -]["notes_cell"].iloc[0] -for workbook_data in cells_to_new_value.split(","): - worksheet_data = workbook_data.split("!") - # worksheet = workbook[worksheet_data[0].replace("'", "")] - worksheet = workbook.Worksheets(worksheet_data[0].replace("'", "")) - # TODO: delete - # is_range = len(worksheet_data[1].split(":")) > 1 - - cell_range = worksheet.Range(worksheet_data[1]).Value = NEW_VALUE +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Create a new QC datasheet from the latest matching workbook, " + "clearing configured cells and writing the batch serial." + ) + ) + parser.add_argument( + "--backend", + choices=("com", "ooxml"), + default=None, + help=( + "Excel edit backend: 'com' (Windows Excel + add-ins) or " + f"'ooxml' (surgical zip edit). Default: {default_backend()}." + ), + ) + return parser.parse_args(argv) -serial_cell = path_df[ - (path_df["set_name"] == selected_set) & (path_df["dir"].str.endswith(selected_dir)) -]["serial_cell"].iloc[0] -for workbook_data in serial_cell.split(","): - worksheet_data = workbook_data.split("!") - worksheet = workbook.Worksheets(worksheet_data[0].replace("'", "")) - cell_range = worksheet.Range(worksheet_data[1]) - cell_range.Value = batch_serial -if not new_workbook_name.is_file(): - pathlib.Path(new_workbook_name.parents[0]).mkdir(parents=True, exist_ok=True) - workbook.SaveAs(str(new_workbook_name)) - excel.WindowState = win32.constants.xlMaximized - # excel.Application.Quit() - # if os.name == "nt": - # os.system(f"start excel.exe \"{new_workbook_name}\"") + +def run(argv: list[str] | None = None) -> int: + args = parse_args(argv) + backend = resolve_backend(args.backend) + content, path_df = load_config() + q1, q2, q3 = content[0], content[1], content[2] + addin_paths = content[3:5] if len(content) >= 5 else [] + + parent_path = list( + path_df.drop_duplicates(subset=["set_name"], keep="first")["set_name"] + ) + + console = Console() + console.print(q1) + selected_set = select(parent_path, cursor_style="cyan") + + console.print(q2) + selected_dir = select( + [ + Path(path).stem + for path in list(path_df[path_df["set_name"] == selected_set]["dir"]) + ] + ) + console.print(f"Selected: {selected_dir}") + + row = path_df[ + (path_df["set_name"] == selected_set) + & (path_df["dir"].str.endswith(selected_dir)) + ].iloc[0] + path_ = Path(row["dir"]) + pattern = row["pattern"] + search_pattern = pattern.replace("[SERIAL]", "*") + files = [str(x) for x in path_.glob(search_pattern) if x.is_file()] + if not files: + console.print(f"[red]No workbooks matching {search_pattern!r} in {path_}[/red]") + return 1 + + batch_serial = prompt(q3, target_type=str) + ref_workbook_name, new_workbook_name = get_workbook_names( + files, batch_serial, path_, pattern + ) + console.print(f"Selected: {Path(ref_workbook_name).stem}") + console.print(f"Backend: {backend}") + + if new_workbook_name.is_file(): + console.print(f"[yellow]Destination already exists, skipping: {new_workbook_name}[/yellow]") + return 0 + + cells_to_clear = row["cells_to_clear"] + notes_cell = row["notes_cell"] + serial_cell = row["serial_cell"] + + if backend == "com": + from xlsx_clean.com_backend import clean_workbook_com + + with tempfile.TemporaryDirectory(prefix="xlsx_clean_") as tmp: + temp_workbook = Path(tmp) / "temp_workbook.xlsx" + shutil.copyfile(ref_workbook_name, temp_workbook) + clean_workbook_com( + source=temp_workbook, + destination=new_workbook_name, + cells_to_clear=cells_to_clear, + notes_cell=notes_cell, + serial_cell=serial_cell, + batch_serial=batch_serial, + addin_paths=addin_paths, + notes_value=NEW_VALUE, + ) + else: + from xlsx_clean.ooxml_backend import clean_workbook_ooxml + + clean_workbook_ooxml( + source=ref_workbook_name, + destination=new_workbook_name, + cells_to_clear=cells_to_clear, + notes_cell=notes_cell, + serial_cell=serial_cell, + batch_serial=batch_serial, + notes_value=NEW_VALUE, + ) + + console.print(f"[green]Wrote {new_workbook_name}[/green]") + return 0 + + +def main() -> None: + raise SystemExit(run()) + + +if __name__ == "__main__": + main() diff --git a/src/xlsx_clean/com_backend.py b/src/xlsx_clean/com_backend.py new file mode 100644 index 0000000..05f031a --- /dev/null +++ b/src/xlsx_clean/com_backend.py @@ -0,0 +1,64 @@ +"""Windows Excel COM backend (pywin32). Imported only when selected.""" + +from __future__ import annotations + +from pathlib import Path + + +def clean_workbook_com( + source: Path | str, + destination: Path | str, + cells_to_clear: str, + notes_cell: str, + serial_cell: str, + batch_serial: str, + addin_paths: list[str] | None = None, + notes_value: str = "", + visible: bool = True, + maximize: bool = True, +) -> None: + """Clear/set cells via Excel COM, SaveAs destination, leave Excel open.""" + # Lazy import so Linux never loads pywin32. + import win32com.client as win32 + + source = Path(source) + destination = Path(destination) + destination.parent.mkdir(parents=True, exist_ok=True) + + # AttributeError: ... has no attribute 'CLSIDToClassMap' + # https://stackoverflow.com/questions/52889704 + excel = win32.gencache.EnsureDispatch("Excel.Application") + excel.Visible = visible + + workbook = excel.Workbooks.Open(str(source.resolve())) + for addin_path in addin_paths or []: + if addin_path: + excel.Workbooks.Open(addin_path) + + for workbook_data in cells_to_clear.split(","): + workbook_data = workbook_data.strip() + if not workbook_data: + continue + sheet_name, a1 = workbook_data.split("!", 1) + worksheet = workbook.Worksheets(sheet_name.replace("'", "")) + worksheet.Range(a1).ClearContents() + + for workbook_data in notes_cell.split(","): + workbook_data = workbook_data.strip() + if not workbook_data: + continue + sheet_name, a1 = workbook_data.split("!", 1) + worksheet = workbook.Worksheets(sheet_name.replace("'", "")) + worksheet.Range(a1).Value = notes_value + + for workbook_data in serial_cell.split(","): + workbook_data = workbook_data.strip() + if not workbook_data: + continue + sheet_name, a1 = workbook_data.split("!", 1) + worksheet = workbook.Worksheets(sheet_name.replace("'", "")) + worksheet.Range(a1).Value = batch_serial + + workbook.SaveAs(str(destination.resolve())) + if maximize: + excel.WindowState = win32.constants.xlMaximized diff --git a/src/xlsx_clean/new_xslx.bat b/src/xlsx_clean/new_xslx.bat index 7776494..c56975e 100644 --- a/src/xlsx_clean/new_xslx.bat +++ b/src/xlsx_clean/new_xslx.bat @@ -1 +1,2 @@ -python .\clean_cells.py \ No newline at end of file +@echo off +python -m xlsx_clean.clean_cells %* diff --git a/src/xlsx_clean/ooxml_backend.py b/src/xlsx_clean/ooxml_backend.py new file mode 100644 index 0000000..e742926 --- /dev/null +++ b/src/xlsx_clean/ooxml_backend.py @@ -0,0 +1,362 @@ +"""Surgical OOXML edits that preserve non-worksheet package parts. + +Unlike openpyxl load/save, this rewrites only worksheet XML (and optionally +drops calcChain) so connections, queries, styles, drawings, etc. stay intact. +""" + +from __future__ import annotations + +import io +import re +import zipfile +from pathlib import Path +from typing import Iterable +from xml.etree import ElementTree as ET + +MAIN_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main" +REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships" +OFFICE_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" +WORKSHEET_REL_TYPE = f"{OFFICE_REL_NS}/worksheet" + +ET.register_namespace("", MAIN_NS) +ET.register_namespace("r", OFFICE_REL_NS) + +NS = {"m": MAIN_NS, "r": REL_NS, "pr": OFFICE_REL_NS} + +_CELL_REF_RE = re.compile(r"^([A-Za-z]+)(\d+)$") + + +def _q(tag: str) -> str: + return f"{{{MAIN_NS}}}{tag}" + + +def col_letters_to_index(letters: str) -> int: + result = 0 + for ch in letters.upper(): + result = result * 26 + (ord(ch) - ord("A") + 1) + return result + + +def index_to_col_letters(index: int) -> str: + letters = [] + while index: + index, rem = divmod(index - 1, 26) + letters.append(chr(ord("A") + rem)) + return "".join(reversed(letters)) + + +def parse_cell_ref(ref: str) -> tuple[str, int]: + match = _CELL_REF_RE.match(ref.strip()) + if not match: + raise ValueError(f"Invalid cell reference: {ref!r}") + return match.group(1).upper(), int(match.group(2)) + + +def expand_a1_range(a1: str) -> list[str]: + """Expand 'F2', 'F2:F3', or 'E12:G12' into individual A1 refs.""" + a1 = a1.strip() + if ":" not in a1: + col, row = parse_cell_ref(a1) + return [f"{col}{row}"] + + start, end = a1.split(":", 1) + start_col, start_row = parse_cell_ref(start) + end_col, end_row = parse_cell_ref(end) + c0, c1 = col_letters_to_index(start_col), col_letters_to_index(end_col) + r0, r1 = start_row, end_row + if c0 > c1: + c0, c1 = c1, c0 + if r0 > r1: + r0, r1 = r1, r0 + + refs: list[str] = [] + for row in range(r0, r1 + 1): + for col in range(c0, c1 + 1): + refs.append(f"{index_to_col_letters(col)}{row}") + return refs + + +def parse_sheet_cell_ref(spec: str) -> tuple[str, str]: + """Parse 'Batch!F2:F3' or \"'KW'!C3:C4\" into (sheet_name, a1_range).""" + spec = spec.strip() + if "!" not in spec: + raise ValueError(f"Expected Sheet!A1 reference, got {spec!r}") + sheet, a1 = spec.split("!", 1) + sheet = sheet.strip().strip("'").strip('"') + return sheet, a1.strip() + + +def _sheet_targets(zf: zipfile.ZipFile) -> dict[str, str]: + """Map sheet name -> zip member path (e.g. xl/worksheets/sheet1.xml).""" + workbook_xml = ET.fromstring(zf.read("xl/workbook.xml")) + rels_xml = ET.fromstring(zf.read("xl/_rels/workbook.xml.rels")) + + rel_id_to_target: dict[str, str] = {} + for rel in rels_xml.findall("r:Relationship", NS): + if rel.get("Type") != WORKSHEET_REL_TYPE: + continue + rid = rel.get("Id") + target = rel.get("Target") + if not rid or not target: + continue + # Targets are relative to xl/ + target = target.lstrip("/") + if not target.startswith("xl/"): + target = f"xl/{target}" + rel_id_to_target[rid] = target + + name_to_path: dict[str, str] = {} + sheets = workbook_xml.find("m:sheets", NS) + if sheets is None: + return name_to_path + for sheet in sheets.findall("m:sheet", NS): + name = sheet.get("name") + rid = sheet.get(f"{{{OFFICE_REL_NS}}}id") + if name and rid and rid in rel_id_to_target: + name_to_path[name] = rel_id_to_target[rid] + return name_to_path + + +def _find_row(sheet_root: ET.Element, row_num: int) -> ET.Element | None: + sheet_data = sheet_root.find("m:sheetData", NS) + if sheet_data is None: + return None + for row in sheet_data.findall("m:row", NS): + if row.get("r") == str(row_num): + return row + return None + + +def _ensure_sheet_data(sheet_root: ET.Element) -> ET.Element: + sheet_data = sheet_root.find("m:sheetData", NS) + if sheet_data is not None: + return sheet_data + sheet_data = ET.SubElement(sheet_root, _q("sheetData")) + return sheet_data + + +def _ensure_row(sheet_root: ET.Element, row_num: int) -> ET.Element: + existing = _find_row(sheet_root, row_num) + if existing is not None: + return existing + + sheet_data = _ensure_sheet_data(sheet_root) + new_row = ET.Element(_q("row"), {"r": str(row_num)}) + # Insert in row-number order + inserted = False + for idx, row in enumerate(list(sheet_data)): + if row.tag != _q("row"): + continue + r_attr = row.get("r") + if r_attr is not None and int(r_attr) > row_num: + sheet_data.insert(idx, new_row) + inserted = True + break + if not inserted: + sheet_data.append(new_row) + return new_row + + +def _find_cell(row: ET.Element, ref: str) -> ET.Element | None: + for cell in row.findall("m:c", NS): + if cell.get("r") == ref: + return cell + return None + + +def _ensure_cell(row: ET.Element, ref: str) -> ET.Element: + existing = _find_cell(row, ref) + if existing is not None: + return existing + + col_letters, _ = parse_cell_ref(ref) + col_idx = col_letters_to_index(col_letters) + new_cell = ET.Element(_q("c"), {"r": ref}) + inserted = False + for idx, cell in enumerate(list(row)): + if cell.tag != _q("c"): + continue + cell_ref = cell.get("r") + if not cell_ref: + continue + other_col, _ = parse_cell_ref(cell_ref) + if col_letters_to_index(other_col) > col_idx: + row.insert(idx, new_cell) + inserted = True + break + if not inserted: + row.append(new_cell) + return new_cell + + +def _clear_cell_contents(cell: ET.Element) -> None: + """Clear value/formula like Excel ClearContents; keep style attrs.""" + # Drop type/value-related attrs; keep r and s (style). + for attr in list(cell.attrib): + if attr not in ("r", "s", "cm", "vm", "ph"): + del cell.attrib[attr] + for child in list(cell): + cell.remove(child) + + +def _set_cell_string(cell: ET.Element, value: str) -> None: + """Set an inline string value, preserving style attribute when present.""" + style = cell.get("s") + _clear_cell_contents(cell) + if style is not None: + cell.set("s", style) + if value == "": + # Empty string: leave cell present with style only (cleared). + return + cell.set("t", "inlineStr") + is_el = ET.SubElement(cell, _q("is")) + t_el = ET.SubElement(is_el, _q("t")) + t_el.text = value + if value.startswith(" ") or value.endswith(" ") or "\n" in value: + t_el.set("{http://www.w3.org/XML/1998/namespace}space", "preserve") + + +def _sheet_xml_tostring(root: ET.Element) -> bytes: + # Preserve XML declaration; Excel is picky about namespaces on worksheets. + body = ET.tostring(root, encoding="utf-8", xml_declaration=True) + return body + + +def _apply_ops_to_sheet( + sheet_xml: bytes, + clear_refs: Iterable[str], + set_values: dict[str, str], +) -> bytes: + root = ET.fromstring(sheet_xml) + + for ref in clear_refs: + col, row_num = parse_cell_ref(ref) + row = _find_row(root, row_num) + if row is None: + continue + cell = _find_cell(row, f"{col}{row_num}") + if cell is not None: + _clear_cell_contents(cell) + + for ref, value in set_values.items(): + col, row_num = parse_cell_ref(ref) + row = _ensure_row(root, row_num) + cell = _ensure_cell(row, f"{col}{row_num}") + _set_cell_string(cell, value) + + return _sheet_xml_tostring(root) + + +def apply_cell_edits( + source: Path | str, + destination: Path | str, + clear_specs: Iterable[str], + set_specs: dict[str, str], +) -> None: + """Copy source workbook to destination with surgical cell edits. + + clear_specs: iterable of 'Sheet!A1:B2' ranges to ClearContents. + set_specs: mapping of 'Sheet!A1' -> string value to write. + """ + source = Path(source) + destination = Path(destination) + destination.parent.mkdir(parents=True, exist_ok=True) + + clears_by_sheet: dict[str, list[str]] = {} + for spec in clear_specs: + sheet, a1 = parse_sheet_cell_ref(spec) + clears_by_sheet.setdefault(sheet, []).extend(expand_a1_range(a1)) + + sets_by_sheet: dict[str, dict[str, str]] = {} + for spec, value in set_specs.items(): + sheet, a1 = parse_sheet_cell_ref(spec) + refs = expand_a1_range(a1) + sheet_sets = sets_by_sheet.setdefault(sheet, {}) + for ref in refs: + sheet_sets[ref] = value + + touched_sheets = set(clears_by_sheet) | set(sets_by_sheet) + + with zipfile.ZipFile(source, "r") as zin: + name_to_path = _sheet_targets(zin) + missing = sorted(touched_sheets - set(name_to_path)) + if missing: + raise KeyError(f"Worksheet(s) not found in workbook: {missing}") + + rewritten: dict[str, bytes] = {} + for sheet_name in touched_sheets: + member = name_to_path[sheet_name] + rewritten[member] = _apply_ops_to_sheet( + zin.read(member), + clears_by_sheet.get(sheet_name, []), + sets_by_sheet.get(sheet_name, {}), + ) + + # Drop calcChain so Excel rebuilds after formula clears, and scrub + # dangling Content_Types / workbook rels entries that pointed at it. + skip = {"xl/calcChain.xml"} + if "xl/calcChain.xml" in zin.namelist(): + if "[Content_Types].xml" in zin.namelist(): + rewritten["[Content_Types].xml"] = _strip_calc_chain_content_types( + zin.read("[Content_Types].xml") + ) + if "xl/_rels/workbook.xml.rels" in zin.namelist(): + rewritten["xl/_rels/workbook.xml.rels"] = _strip_calc_chain_rels( + zin.read("xl/_rels/workbook.xml.rels") + ) + + with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as zout: + for info in zin.infolist(): + if info.filename in skip: + continue + if info.filename in rewritten: + zout.writestr(info, rewritten[info.filename]) + else: + zout.writestr(info, zin.read(info.filename)) + + +def _strip_calc_chain_content_types(data: bytes) -> bytes: + """Remove calcChain Override without rewriting package namespaces.""" + text = data.decode("utf-8") + text = re.sub( + r'\s*<[^>]*PartName="[^"]*calcChain\.xml"[^>]*/>', + "", + text, + flags=re.IGNORECASE, + ) + return text.encode("utf-8") + + +def _strip_calc_chain_rels(data: bytes) -> bytes: + """Remove calcChain Relationship without rewriting package namespaces.""" + text = data.decode("utf-8") + text = re.sub( + r'\s*<[^>]*Target="[^"]*calcChain\.xml"[^>]*/>', + "", + text, + flags=re.IGNORECASE, + ) + return text.encode("utf-8") + + +def clean_workbook_ooxml( + source: Path | str, + destination: Path | str, + cells_to_clear: str, + notes_cell: str, + serial_cell: str, + batch_serial: str, + notes_value: str = "", +) -> None: + """High-level OOXML backend matching the COM clean sequence.""" + clear_specs = [part.strip() for part in cells_to_clear.split(",") if part.strip()] + set_specs: dict[str, str] = {} + for part in notes_cell.split(","): + part = part.strip() + if part: + set_specs[part] = notes_value + for part in serial_cell.split(","): + part = part.strip() + if part: + set_specs[part] = batch_serial + apply_cell_edits(source, destination, clear_specs, set_specs) diff --git a/src/xlsx_clean/paths.py b/src/xlsx_clean/paths.py new file mode 100644 index 0000000..5814df8 --- /dev/null +++ b/src/xlsx_clean/paths.py @@ -0,0 +1,63 @@ +"""Config and path helpers for cross-platform workbook roots.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +PACKAGE_DIR = Path(__file__).resolve().parent + +# Historical Windows root used in file_data.csv +DEFAULT_OPENCLOUD_ROOT = Path(r"D:\OpenCloud") +OPENCLOUD_MARKER = "OpenCloud" + + +def package_file(name: str) -> Path: + return PACKAGE_DIR / name + + +def get_opencloud_root() -> Path: + """Workbook tree root from XLSX_CLEAN_ROOT, else D:\\OpenCloud on Windows.""" + env = os.environ.get("XLSX_CLEAN_ROOT") + if env: + return Path(env) + return DEFAULT_OPENCLOUD_ROOT + + +def remap_opencloud_path(path_str: str, root: Path | None = None) -> Path: + """Map a CSV path under OpenCloud onto the configured root. + + Examples: + D:\\OpenCloud\\inco\\... + root=/data -> /data/inco/... + Relative paths without OpenCloud are returned as-is (Path). + """ + if root is None: + root = get_opencloud_root() + + normalized = path_str.replace("\\", "/") + # Case-insensitive marker search + lower = normalized.lower() + marker = f"{OPENCLOUD_MARKER.lower()}/" + idx = lower.find(marker) + if idx != -1: + rel = normalized[idx + len(marker) :] + return root / rel + + # Already relative to root-style path without drive + return Path(path_str) + + +def default_backend() -> str: + return "com" if sys.platform == "win32" else "ooxml" + + +def resolve_backend(requested: str | None) -> str: + backend = (requested or default_backend()).lower() + if backend not in {"com", "ooxml"}: + raise ValueError(f"Unknown backend {backend!r}; use 'com' or 'ooxml'") + if backend == "com" and sys.platform != "win32": + raise RuntimeError( + "COM backend requires Windows with Microsoft Excel and pywin32" + ) + return backend