Create or edit Excel workbooks with openpyxl-specific pitfall handling, anchored preflight audit, and deterministic post-write proof that every criterion is satisfied
61
72%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
View guide
Passed
No findings from the security scan
Fix and improve this skill with Tessl
tessl review fix ./benchmarks/gdpval/skills/spreadsheet-proof-gate-merged-fedf41/SKILL.mdUse this skill when you must create from scratch or modify an Excel workbook and the result must be proven against a user specification rather than merely described.
This skill extends the spreadsheet-proof-gate methodology with explicit support for:
This is a workflow skill requiring a direct Python verification pass with openpyxl before reporting success. The verification script must be saved to a .py file and executed via run_shell (NOT execute_code_sandbox).
Use this skill when ANY of the following are true:
Before starting, determine which path applies:
Creation path (new workbook):
Editing path (existing workbook):
The following openpyxl-specific issues must be handled explicitly:
MergedCell errors:
.value on merged cells raises MergedCell exceptionws.merged_cells.ranges and handle merged regions speciallyWorksheet creation patterns:
wb.create_sheet() is the correct method, not direct assignment\ / ? * [ ]) are not allowed in sheet namesFormula handling:
data_only=False when loading to preserve formulaswb.save() after modifications, not wb.close()Cell value type handling:
cell.value not direct cell access for safetyA workbook task is only complete when:
PASS, FAIL, or UNAVAILABLE-IN-SOURCEAll discovery, reads, writes, and verification must be anchored to the exact workspace path provided for the task.
Your output should be based on proof, not inference.
For every task using this workflow, maintain these artifacts internally:
The post-write proof checklist is decisive.
from pathlib import Path
target_path = Path("path/to/workbook.xlsx")
exists = target_path.exists()If exists == False and user expects to create new workbook:
If exists == True and user expects to edit:
If exists == False but user expects to edit:
For creation path, confirm:
Before writing any code, document:
Merged cell planning:
Sheet name validation:
\ / ? * [ ]Data type planning:
datetime objects, not stringsSearch under the exact workspace root for plausible Excel files:
.xlsx, .xlsm, .xlsConfirm:
from openpyxl import load_workbook
# Always use data_only=False to preserve formulas
wb = load_workbook(target_path, data_only=False)
# Get all sheet names
sheet_names = wb.sheetnames
# For each sheet, inspect safely
for ws in wb.worksheets:
# Check for merged cells BEFORE accessing values
merged_ranges = list(ws.merged_cells.ranges)
# Get headers safely
headers = []
for cell in ws[1]: # Row 1
# Check if cell is part of a merged range
is_merged = any(cell.coordinate in mr for mr in merged_ranges)
if is_merged:
# Get value from top-left of merged range
for mr in merged_ranges:
if cell.coordinate in mr:
headers.append(ws[mr.min_row][mr.min_col - 1].value)
break
else:
headers.append(cell.value)If you inspect the workbook multiple times:
Before editing/creating, extract every verifiable requirement.
For creation tasks:
output-exists: workbook created at <path>required-sheet: <name> existsrequired-column: Sheet <name> has column "<column>"row-count: Sheet <name> has exactly N data rowsdata-populated: Column <X> contains values for all data rowsformula: Column <Y> contains formulasmerged-region: Sheet <name> has merged range <range>For editing tasks:
preservation: Sheet <name> still exists unchangedunchanged-sheets: <list> were not modifiedmacro-preservation: VBA macros preserved (if applicable)required-sheet: Summary existsrequired-column: Sheet Sample has column "Selected"row-count: exactly 25 data rows in Sampleformula: column H contains formulas for all populated rowsmerged-region: Summary A1:B1 is mergedworkbook looks rightsampling seems okaymost tabs presentProceed only if ALL are true:
For creation:
For editing:
For both:
Otherwise, stop and report the mismatch.
from openpyxl import Workbook
wb = Workbook()
# Remove default sheet if creating custom structure
if 'Sheet' in wb.sheetnames:
del wb['Sheet']
# Create sheets with validated names
for sheet_name in planned_sheets:
ws = wb.create_sheet(title=sheet_name)
# Populate headers
for col_idx, header in enumerate(headers, start=1):
ws.cell(row=1, column=col_idx, value=header)
# Populate data rows
for row_idx, row_data in enumerate(data_rows, start=2):
for col_idx, value in enumerate(row_data, start=1):
ws.cell(row=row_idx, column=col_idx, value=value)
# Apply merges if planned
for merge_range in planned_merges:
ws.merge_cells(merge_range)
wb.save(output_path)from openpyxl import load_workbook
wb = load_workbook(target_path, data_only=False)
ws = wb[sheet_name]
# Handle merged cells when reading
merged_ranges = list(ws.merged_cells.ranges)
# When modifying, be careful with merged regions
# Don't write to cells within merged ranges (except top-left)
# Modify content
ws.cell(row=row, column=col, value=new_value)
# Add new sheet if needed
if new_sheet_name not in wb.sheetnames:
wb.create_sheet(title=new_sheet_name)
wb.save(output_path)This phase is mandatory.
After saving, directly inspect the saved workbook from disk with Python and openpyxl. Do not finalize from memory, delegated prose, or a generic success message.
from pathlib import Path
from openpyxl import load_workbook
WORKBOOK = Path("TARGET.xlsx")
TRUTHY = {"x", "yes", "true", "1", "y"}
def norm(v):
if v is None:
return ""
return str(v).strip()
def lower(v):
return norm(v).lower()
def first_nonempty_row(ws, max_scan=20):
for r in ws.iter_rows(min_row=1, max_row=min(ws.max_row, max_scan), values_only=True):
vals = list(r)
if any(norm(v) != "" for v in vals):
return vals
return []
def data_rows(ws, header_row_idx=1):
count = 0
for row in ws.iter_rows(min_row=header_row_idx + 1, values_only=True):
if any(norm(v) != "" for v in row):
count += 1
return count
def safe_cell_value(ws, coord, merged_ranges=None):
"""Safely get cell value, handling merged cells"""
cell = ws[coord]
if merged_ranges:
for mr in merged_ranges:
if coord in mr:
# Return value from top-left of merged range
return ws[mr.min_row][mr.min_col - 1].value
return cell.value
print(f"WORKBOOK: {WORKBOOK}")
print(f"EXISTS: {WORKBOOK.exists()}")
if not WORKBOOK.exists():
print("CRITERION|output-exists|FAIL|Workbook file missing")
raise SystemExit(0)
wb = load_workbook(WORKBOOK, data_only=False)
print(f"SHEETS: {wb.sheetnames}")
for ws in wb.worksheets:
merged_ranges = list(ws.merged_cells.ranges)
headers = first_nonempty_row(ws)
print(f"SHEET|{ws.title}|HEADERS|{headers}")
print(f"SHEET|{ws.title}|DATA_ROWS|{data_rows(ws)}")
print(f"SHEET|{ws.title}|MERGED_RANGES|{[str(mr) for mr in merged_ranges]}")
# Check each criterion
# Example:
# required_sheets = ["Summary", "Data"]
# for sheet in required_sheets:
# status = "PASS" if sheet in wb.sheetnames else "FAIL"
# print(f"CRITERION|required-sheet-{sheet}|{status}|Sheet {sheet} {'found' if status == 'PASS' else 'missing'}")
# Print all criteria with status
for criterion_line in criteria:
print(criterion_line)The verification must report:
Each criterion must end in exactly one status:
PASS — requirement satisfied by direct inspectionFAIL — requirement not satisfiedUNAVAILABLE-IN-SOURCE — requirement could not be satisfied because required source information was absentDo not use softer wording like:
You may finalize only when every required criterion is either:
PASS, orUNAVAILABLE-IN-SOURCE with explicit reconciliationYou must not finalize when:
FAILIf direct proof says the workbook is incomplete, that proof is authoritative.
If execute_code_sandbox or run_shell returns opaque errors:
execute_code_sandbox fails, try run_shell with python scriptrun_shell fails, try execute_code_sandboxshell_agent for autonomous executionMergedCell AttributeError:
.value on merged cells raises exceptionws.merged_cells.ranges before accessing; get value from top-left cellInvalid sheet name:
\ / ? * [ ])Formula parsing errors:
data_only=False when loading; verify formula syntax is Excel-compatibleFile lock/permission errors:
If spreadsheet operations fail repeatedly (>2 attempts):
shell_agent(
task="""
Create/modify Excel workbook at <exact_path>.
Required structure:
- Sheets: <list>
- Columns per sheet: <specification>
- Data to populate: <details>
- Formulas: <specification>
- Merged regions: <if any>
Handle openpyxl pitfalls:
- Check merged_cells.ranges before accessing cell values
- Validate sheet names (31 chars max, no special chars)
- Use data_only=False when loading to preserve formulas
Provide: created file path, sheets created, row counts, any errors encountered.
""",
timeout=300
)Then verify shell_agent output with the Phase 6 proof procedure.
Tool requirement: Write verification script to a .py file and execute via run_shell, NOT execute_code_sandbox. This ensures reliability when sandbox providers are unavailable.
Step 6.1: Write script to disk first
Create a Python file (e.g., verify_workbook.py) with the verification logic, then execute it via shell.
Step 6.2: Execute via run_shell
python verify_workbook.pyStep 6.3: Parse verification output
The script must output explicit PASS/FAIL markers for each criterion.
c5a9c4b
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.