xlsx-to-python-step-1-dual-pass-loading

Sub-skill of xlsx-to-python: Step 1 — Dual-Pass Loading (+5).

5 stars

Best use case

xlsx-to-python-step-1-dual-pass-loading is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Sub-skill of xlsx-to-python: Step 1 — Dual-Pass Loading (+5).

Teams using xlsx-to-python-step-1-dual-pass-loading should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/step-1-dual-pass-loading/SKILL.md --create-dirs "https://raw.githubusercontent.com/vamseeachanta/workspace-hub/main/.agents/skills/_archive/data/office/xlsx-to-python/step-1-dual-pass-loading/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/step-1-dual-pass-loading/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How xlsx-to-python-step-1-dual-pass-loading Compares

Feature / Agentxlsx-to-python-step-1-dual-pass-loadingStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Sub-skill of xlsx-to-python: Step 1 — Dual-Pass Loading (+5).

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Step 1 — Dual-Pass Loading (+5)

## Step 1 — Dual-Pass Loading


```python
from openpyxl import load_workbook

def load_xlsx_dual_pass(filepath: str):
    """Load workbook twice: values + formulas."""
    # Pass 1: computed values (for test assertions)
    wb_values = load_workbook(filepath, data_only=True)

    # Pass 2: formula strings (for implementation)
    wb_formulas = load_workbook(filepath, data_only=False)

    return wb_values, wb_formulas
```

**Critical note:** `data_only=True` reads cached values from the last Excel save.
If the file was saved without recalculation (programmatic exports, LibreOffice,
manual-calc mode), ALL formula cells return `None`. This would silently produce
vacuous tests (`assert result == None`).


## Cache Quality Gate (MANDATORY)


Every formula cell must be classified before test generation:

```python
def classify_cache_quality(formula_cells: list[dict]) -> dict:
    """Classify cache quality for each formula cell."""
    stats = {"total": 0, "ok": 0, "missing": 0, "suspect": 0}
    for cell in formula_cells:
        stats["total"] += 1
        if cell["value"] is None:
            cell["cache_status"] = "cached_missing"
            stats["missing"] += 1
        else:
            cell["cache_status"] = "cached_ok"
            stats["ok"] += 1

    # File-level threshold: >50% missing = uncalculated file
    if stats["total"] > 0 and stats["missing"] / stats["total"] > 0.5:
        return {**stats, "file_status": "uncalculated",
                "action": "skip test generation; use formulas lib as diagnostic fallback"}
    return {**stats, "file_status": "ok", "action": "proceed with test generation"}
```

**Rules:**
- Only `cached_ok` cells emit `pytest.approx()` assertions
- `cached_missing` cells are logged in yield report but produce NO assertions
- If >50% missing, flag file as `uncalculated` — exclude from test generation
- Use `formulas` library as diagnostic fallback only (Excel cached values and
  library-evaluated values answer different questions)


## Step 2 — Formula Cell Identification


```python
def extract_formula_cells(wb_formulas, wb_values):
    """Extract all formula cells with both formula text and computed value."""
    cells = []
    for sheet_name in wb_formulas.sheetnames:
        ws_f = wb_formulas[sheet_name]
        ws_v = wb_values[sheet_name]
        for row in ws_f.iter_rows():
            for cell in row:
                if cell.data_type == 'f' or (
                    isinstance(cell.value, str) and cell.value.startswith('=')
                ):
                    value_cell = ws_v[cell.coordinate]
                    cells.append({
                        "sheet": sheet_name,
                        "ref": cell.coordinate,
                        "formula": cell.value,
                        "value": value_cell.value,
                        "row": cell.row,
                        "col": cell.column,
                    })
    return cells
```


## Step 3 — Named Range Extraction


```python
def extract_named_ranges(wb):
    """Extract all defined names as variable definitions."""
    named_ranges = []
    for defn in wb.defined_names.definedName:
        destinations = list(defn.destinations)
        for sheet_title, cell_ref in destinations:
            named_ranges.append({
                "name": defn.name,
                "sheet": sheet_title,
                "cell_ref": cell_ref,
                "scope": "workbook" if defn.localSheetId is None else sheet_title,
            })
    return named_ranges
```


## Step 4 — Formula Reference Parsing


Parse cell references from Excel formula strings:

```python
import re

# Matches: A1, $A$1, A$1, $A1, Sheet1!A1, 'Sheet Name'!A1
CELL_REF_RE = re.compile(
    r"(?:'([^']+)'!|([A-Za-z_]\w*)!)?"  # optional sheet prefix
    r"(\$?[A-Z]{1,3}\$?\d+)"             # cell reference
    r"(?::(\$?[A-Z]{1,3}\$?\d+))?"       # optional range end
)

def parse_formula_references(formula: str) -> list[str]:
    """Extract cell references from an Excel formula string."""
    refs = []
    for match in CELL_REF_RE.finditer(formula):
        sheet = match.group(1) or match.group(2) or ""
        start_ref = match.group(3).replace("$", "")
        end_ref = match.group(4)
        prefix = f"{sheet}!" if sheet else ""
        refs.append(f"{prefix}{start_ref}")
        if end_ref:
            refs.append(f"{prefix}{end_ref.replace('$', '')}")
    return refs
```


## Step 5 — Dependency Graph & Chain Building


```python
import networkx as nx

def build_dependency_graph(formula_cells: list[dict]) -> nx.DiGraph:
    """Build directed graph: edges point from dependency → dependent."""
    G = nx.DiGraph()
    for cell in formula_cells:
        cell_id = f"{cell['sheet']}!{cell['ref']}"
        G.add_node(cell_id, **cell)
        for ref in parse_formula_references(cell["formula"]):
            # Normalize: add sheet prefix if missing
            if "!" not in ref:
                ref = f"{cell['sheet']}!{ref}"
            G.add_edge(ref, cell_id)
    return G

def classify_cells(G: nx.DiGraph) -> dict:
    """Classify cells into inputs, intermediates, outputs."""
    inputs = [n for n in G.nodes() if G.in_degree(n) == 0]
    outputs = [n for n in G.nodes() if G.out_degree(n) == 0
               and G.in_degree(n) > 0]  # must have a formula
    chain = list(nx.topological_sort(G))
    return {"inputs": inputs, "outputs": outputs, "chain": chain}
```

Related Skills

worktree-pre-push-bypass-for-tier1-checks

5
from vamseeachanta/workspace-hub

Handle workspace-hub integration-branch pushes from isolated git worktrees when the pre-push hook incorrectly assumes sibling tier-1 repos exist under the worktree path.

python-import-path-mismatch-debugging

5
from vamseeachanta/workspace-hub

Diagnose and fix ModuleNotFoundError when a package is installed but imports still fail due to environment/path mismatches

python-import-path-debugging

5
from vamseeachanta/workspace-hub

Diagnose ModuleNotFoundError when a package is installed but still fails to import

financial-site-bypass-workflow

5
from vamseeachanta/workspace-hub

Workflow for accessing restricted financial sites when browser automation is blocked

transport-and-passes

5
from vamseeachanta/workspace-hub

Use when recommending transit for a trip — drive vs train vs fly, rail-pass selection, seat reservations and supplements, drive-time honesty. Invoked by trip-planner.

python-debugpy

5
from vamseeachanta/workspace-hub

Debug Python: pdb REPL + debugpy remote (DAP).

python-project-template

5
from vamseeachanta/workspace-hub

Generate standardized Python project structure with pyproject.toml, UV environment, pytest configuration, and workspace-hub compliance. Creates production-ready project scaffolding.

xlsx-to-python

5
from vamseeachanta/workspace-hub

Convert Excel calculation spreadsheets to Python code — extract formulas, build dependency graphs, generate pytest tests using cell values as assertions, and produce dark-intelligence archive YAMLs.

excel-workbook-to-python-v2

5
from vamseeachanta/workspace-hub

Convert engineering Excel workbooks to Python code using Codex Desktop cowork on Windows. Proven superior quality vs Linux openpyxl extraction (24 vs 7 functions, 81 vs 53 tests). Validated on Ballymore jumper installation analysis.

xlsx

5
from vamseeachanta/workspace-hub

Excel spreadsheet toolkit for creating, reading, and manipulating .xlsx files. Supports formulas, formatting, charts, and financial modeling with industry-standard conventions. Use for data analysis, financial models, reports, and spreadsheet automation.

hidden-folder-audit-step-1-inventory-all-hidden-folders

5
from vamseeachanta/workspace-hub

Sub-skill of hidden-folder-audit: Step 1: Inventory All Hidden Folders (+4).

mkdocs-integration-with-python-package

5
from vamseeachanta/workspace-hub

Sub-skill of mkdocs: Integration with Python Package (+2).