Xlsx

From QvvvvvvQ/skills_leaks · View interactive version

Xlsx is an AI agent skill from the GitHub repository QvvvvvvQ/skills_leaks. Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When GLM needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data,

How to use this skill

Skill file

XLSX creation, editing, and analysis

Overview

A user may ask you to create, edit, or analyze the contents of an .xlsx file. You have different tools and workflows available for different tasks.

Must output excel files.

Important Requirements

Python 3 and openpyxl Required for Excel Generation: You can assume Python 3 as the runtime environment. The openpyxl library is required as the primary tool for creating Excel files, managing styles, and writing formulas.

pandas Utilized for Data Processing: You can utilize pandas for efficient data manipulation and processing tasks. The processed data is subsequently exported to the final Excel file through openpyxl.

LibreOffice Required for Formula Recalculation: You can utilize recalc.py for formula check. You can assume LibreOffice is installed for recalculating formula values using the recalc.py script. The script automatically configures LibreOffice on first run.

Requirements for Outputs

All Excel files

Critical Instruction Protocols

Query Decomposition & Verification

Before generating any code, strictly analyze the user's prompt.

Zero Formula Errors

Preserve Existing Templates (when updating templates)

Financial models

Color Coding Standards

Unless otherwise stated by the user or existing template

Industry-Standard Color Conventions

Number Formatting Standards

Required Format Rules

Formula Construction Rules

Assumptions Placement
Formula Error Prevention
Documentation Requirements for Hardcodes

Style Rules

Implement all styling directly using the python-openpyxl library. The following standards define the visual architecture of the spreadsheets.

Global Layout & Design Principles

Layout & Dimensions

Visual Hierarchy

Font Standards (MUST FOLLOW)

# Font configuration example
from openpyxl.styles import Font

# English content
english_font = Font(name='Times New Roman', size=11)

Title Formatting Rules (MUST FOLLOW)

# ✅ CORRECT Title Style

from openpyxl.styles import Font, Alignment
from openpyxl import Workbook

# Load existing file
wb = Workbook()
sheet = wb.active

title_font = Font(name='Times New Roman', size=18, bold=True, color="000000")
title_alignment = Alignment(horizontal='left', vertical='center')

sheet['B2'] = "Report Title"
sheet['B2'].font = title_font
sheet['B2'].alignment = title_alignment
# NO fill applied - title has no background shading

# ❌ WRONG - Do NOT use background shading on titles
# title_fill = PatternFill(start_color="333333", fill_type="solid")  # FORBIDDEN
# sheet['B2'].fill = title_fill  # FORBIDDEN

Visual Themes

1. Default Style

Use for: All non-financial tasks (General data, project management, inventories).

Color Palette Constraints

# Palette
from openpyxl.styles import Alignment, Border, Font, Side, PatternFill, 

# Base & Accents
background_white = "FFFFFF"           # background
background_row_alt = "E9E9E9"         # Alternating row fill
grey_header = "333333"   # Section headers
border_grey = "E3DEDE"        # Standard borders
blue_primary = "0B5CAD"       # Primary Accent

# Application Example: Data Headers (NOT Titles)
header_fill = PatternFill(start_color=grey_header, end_color=grey_header, fill_type="solid")
header_font = Font(name='Times New Roman', color="FFFFFF", bold=True)

for cell in sheet['B3:E3'][0]:
    cell.fill = header_fill
    cell.font = header_font

# Example: Title style (NO shading, left-aligned)
title_font = Font(name='Times New Roman', size=18, bold=True, color="000000")
title_alignment = Alignment(horizontal='left', vertical='center')
sheet['B2'].font = title_font
sheet['B2'].alignment = title_alignment
# NO fill for titles
2. Professional Finance Style

Use for: Financial, fiscal, and market analysis (Stock data, GDP, Budgets, P&L, ROI).

Market Data Color Convention (Critical)

Apply the following color logic based on the target region:

| Region | Price Up / Positive | Price Down / Negative |

| --- | --- | --- |

| China (Mainland) | Red | Green |

| International | Green | Red |

# Professional Finance Palette
from openpyxl.styles import PatternFill, Font

text_dark = "000000"
background_light = "E6E8EB"
header_fill_blue = "1B3F66"
metrics_highlight_warm = "F5E6D3"
negative_red = "FF0000"


# Data Headers Example
pfs_header_fill = PatternFill(start_color=header_fill_blue, end_color=header_fill_blue, fill_type="solid")
pfs_header_font = Font(name='Times New Roman', color="FFFFFF", bold=True)

for cell in sheet['B3:E3'][0]:
    cell.fill = pfs_header_fill
    cell.font = pfs_header_font


# Default font - Times New Roman for English
default_font = Font(name='Times New Roman', size=11, color=text_dark)

# Example: Title style (NO shading, left-aligned)
# NO fill for titles
title_font = Font(name='Times New Roman', size=18, bold=True, color="000000")
title_alignment = Alignment(horizontal='left', vertical='center')
sheet['B2'].font = title_font
sheet['B2'].alignment = title_alignment

# Example: Apply header style (for data headers, NOT titles)
header_fill = PatternFill(start_color=grey_header, end_color=grey_header, fill_type="solid")
header_font = Font(name='Times New Roman', color="FFFFFF", bold=True)
for cell in sheet['B3:E3'][0]:  # Data headers, not title row
    cell.fill = header_fill
    cell.font = header_font

Content Color Conventions

Apply specific font colors to indicate data source and functionality (consistent with Financial Model requirements):

Chart Creation Notes

1. Data Source Must Contain “Actual Values”

2. Reference Range Must Match Title Settings

If this row is empty or contains numeric data, it may result in incorrect series names or data misalignment.

3. Impact of “Visibility” on Chart Data

You must explicitly disable the “plot visible cells only” option, otherwise the chart will appear blank.

# After hiding auxiliary data rows, for each chart object,
# set plot_visible_only to False. This line is required.
chart.plot_visible_only = False

Workflows

Reading and analyzing data

Data analysis with pandas

For data analysis, visualization, and basic operations, use pandas which provides powerful data manipulation capabilities:

import pandas as pd

# Read Excel
df = pd.read_excel('file.xlsx')  # Default: first sheet
all_sheets = pd.read_excel('file.xlsx', sheet_name=None)  # All sheets as dict

# Analyze
df.head()      # Preview data
df.info()      # Column info
df.describe()  # Statistics

# Write Excel
df.to_excel('output.xlsx', index=False)

Excel File Workflows

CRITICAL: Use Formulas, Not Hardcoded Values

Always use Excel formulas instead of calculating values in Python and hardcoding them. This ensures the spreadsheet remains dynamic and updateable.

❌ WRONG - Hardcoding Calculated Values

# Bad: Calculating in Python and hardcoding result
total = df['Sales'].sum()
sheet['B10'] = total  # Hardcodes 5000

# Bad: Computing growth rate in Python
growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
sheet['C5'] = growth  # Hardcodes 0.15

# Bad: Python calculation for average
avg = sum(values) / len(values)
sheet['D20'] = avg  # Hardcodes 42.5

✅ CORRECT - Using Excel Formulas

# Good: Let Excel calculate the sum
sheet['B10'] = '=SUM(B2:B9)'

# Good: Growth rate as Excel formula
sheet['C5'] = '=(C4-C2)/C2'

# Good: Average using Excel function
sheet['D20'] = '=AVERAGE(D2:D19)'

This applies to ALL calculations - totals, percentages, ratios, differences, etc. The spreadsheet should be able to recalculate when source data changes.

Common Workflow

  1. Choose tool: pandas for data, openpyxl for formulas/formatting
  2. Think and Plan: Plan all sheets structure, formulas, cross-references before coding
  3. Create/Load: Create new workbook or load existing file
  4. Modify: Add/edit data, formulas, and formatting
  5. Save: Write to file
  6. Recalculate formulas (MANDATORY IF USING FORMULAS): Use the recalc.py script

```bash

python recalc.py output.xlsx

```

  1. Verify and fix any errors:

Creating new Excel files

# Using openpyxl for formulas and formatting
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment

wb = Workbook()
sheet = wb.active

# Add data
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
sheet.append(['Row', 'of', 'data'])

# Add formula
sheet['B2'] = '=SUM(A1:A10)'

# Formatting
sheet['A1'].font = Font(bold=True, color='FF0000')
sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
sheet['A1'].alignment = Alignment(horizontal='center')

# Column width
sheet.column_dimensions['A'].width = 20

wb.save('output.xlsx')

Editing existing Excel files

# Using openpyxl to preserve formulas and formatting
from openpyxl import load_workbook

# Load existing file
wb = load_workbook('existing.xlsx')
sheet = wb.active  # or wb['SheetName'] for specific sheet

# Working with multiple sheets
for sheet_name in wb.sheetnames:
    sheet = wb[sheet_name]
    print(f"Sheet: {sheet_name}")

# Modify cells
sheet['A1'] = 'New Value'
sheet.insert_rows(2)  # Insert row at position 2
sheet.delete_cols(3)  # Delete column 3

# Add new sheet
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'

wb.save('modified.xlsx')

Recalculating formulas

Excel files created or modified by openpyxl contain formulas as strings but not calculated values. Use the provided recalc.py script to recalculate formulas:

python recalc.py <excel_file> [timeout_seconds]

Example:

python recalc.py output.xlsx 30

The script:

Formula Verification Checklist

Quick checks to ensure formulas work correctly:

Essential Verification

Common Pitfalls

Formula Testing Strategy

Interpreting recalc.py Output

The script returns JSON with error details:

{
  "status": "success",           // or "errors_found"
  "total_errors": 0,              // Total error count
  "total_formulas": 42,           // Number of formulas in file
  "error_summary": {              // Only present if errors found
    "#REF!": {
      "count": 2,
      "locations": ["Sheet1!B5", "Sheet1!C10"]
    }
  }
}

Best Practices

Library Selection

Working with openpyxl

Working with pandas

Code Style Guidelines

IMPORTANT: When generating Python code for Excel operations:

For Excel files themselves:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.