📊xlsx
- プラグイン
- document-skills
- ライセンス
- Proprietary. LICENSE.txt has complete terms
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: スプレッドシートファイルが主な入力または出力となるすべての場面。 具体的には、ユーザーが以下のいずれかを行いたい場合が該当します: - 既存の `.xlsx`、`.xlsm`、`.csv`、`.tsv` ファイルを開く・読み取る・編集する・修正する (例: 列の追加、数式の計算、書式設定、グラフ作成、乱雑なデータのクレンジングなど) - 新しいスプレッドシートをゼロから、または他のデータソースから作成する - 表形式ファイルフォーマット間の変換を行う また、ユーザーがスプレッドシートファイルをファイル名やパスで参照している場合 (「ダウンロードフォルダにある xlsx」のようなカジュアルな表現も含む)、 そのファイルに対して何らかの操作を行いたい、またはそのファイルから何かを生成したい場合にも起動してください。 さらに、乱雑な表形式データファイル(不正な行、ヘッダーの位置ズレ、不要データなど)を 正しいスプレッドシートへクレンジング・再構造化する場合にも起動してください。 **成果物はスプレッドシートファイルでなければなりません。** 以下の場合は起動しないでください: 表形式データが関係していても、主な成果物が Word 文書・HTML レポート・単独の Python スクリプト・データベースパイプライン・Google Sheets API 連携である場合。
原文を表示
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.
ユースケース
- ✓既存のスプレッドシートファイルを開く・読み取る
- ✓スプレッドシートを編集・修正する
- ✓新しいスプレッドシートを作成する
- ✓表形式ファイル形式を変換する
- ✓乱雑なデータをクレンジングする
本文(日本語訳)
出力物の要件
すべてのExcelファイル共通
プロフェッショナルなフォント
- ユーザーから別途指示がない限り、すべての成果物に統一された専門的なフォント(例: Arial、Times New Roman)を使用すること
数式エラーゼロ
- すべてのExcelモデルは、数式エラー(#REF!、#DIV/0!、#VALUE!、#N/A、#NAME?)がゼロ件の状態で納品しなければならない
既存テンプレートの保持(テンプレートを更新する場合)
- 既存ファイルを修正する際は、現在のフォーマット・スタイル・表記規則を十分に確認し、完全に一致させること
- 既存の体裁が確立されているファイルに、標準化されたフォーマットを一方的に適用しないこと
- 既存テンプレートの規則は、常にこれらのガイドラインより優先される
ファイナンシャルモデル
カラーコーディング基準
ユーザーまたは既存テンプレートによる別途の指定がない限り、以下を適用する
業界標準のカラー規則
- 青文字(RGB: 0, 0, 255): ハードコードされた入力値、およびシナリオ分析でユーザーが変更する数値
- 黒文字(RGB: 0, 0, 0): すべての数式および計算結果
- 緑文字(RGB: 0, 128, 0): 同一ワークブック内の別ワークシートから参照するリンク
- 赤文字(RGB: 255, 0, 0): 他のファイルへの外部リンク
- 黄色背景(RGB: 255, 255, 0): 注意が必要な主要な前提条件、または更新が必要なセル
数値フォーマット基準
必須のフォーマットルール
- 年度: テキスト文字列として表示(例: "2024"、"2,024" は不可)
- 金額:
$#,##0形式を使用。ヘッダーには必ず単位を明記(例: "Revenue ($mm)") - ゼロ値: パーセンテージを含むすべてのゼロをハイフン "-" で表示するよう数値フォーマットを設定(例:
$#,##0;($#,##0);-) - パーセンテージ: 小数点第1位までの
0.0%形式をデフォルトとする - 倍率: バリュエーション倍率(EV/EBITDA、P/E 等)は
0.0x形式で表示 - 負の数: マイナス記号(-123)ではなく括弧表記(123)を使用
数式の作成ルール
前提条件の配置
- 成長率・マージン・倍率等、すべての前提条件は専用の前提条件セルに配置すること
- 数式内には直接数値を入力せず、セル参照を使用すること
- 例:
=B5*1.05ではなく=B5*(1+$B$6)を使用する
数式エラーの防止
- すべてのセル参照が正しいことを確認する
- 範囲のオフバイワンエラーに注意する
- すべての予測期間にわたって数式の一貫性を確保する
- エッジケース(ゼロ値・負の数)でテストを行う
- 意図しない循環参照がないことを確認する
ハードコード値のドキュメント要件
- セルへのコメント、またはテーブル末尾の場合は隣接するセルに出典を記載する。
書式:
"Source: [システム/ドキュメント], [日付], [具体的な参照箇所], [該当するURL]" - 記載例:
"Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]""Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]""Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity""Source: FactSet, 8/20/2025, Consensus Estimates Screen"
XLSXファイルの作成・編集・分析
概要
ユーザーから .xlsx ファイルの作成・編集・内容分析を依頼される場合があります。
タスクの種類に応じて、使用できるツールとワークフローが異なります。
重要な要件
数式再計算にはLibreOfficeが必要:
scripts/recalc.py スクリプトを使用して数式の値を再計算するため、LibreOfficeがインストールされていることを前提とします。
このスクリプトは初回実行時にLibreOfficeを自動設定します。Unixソケットが制限されたサンドボックス環境においても対応しています(scripts/office/soffice.py により処理)。
データの読み込みと分析
pandasによるデータ分析
データ分析・可視化・基本操作には、強力なデータ操作機能を持つ pandas を使用します:
import pandas as pd
# Excelの読み込み
df = pd.read_excel('file.xlsx') # デフォルト: 先頭シート
all_sheets = pd.read_excel('file.xlsx', sheet_name=None) # 全シートを辞書として取得
# 分析
df.head() # データのプレビュー
df.info() # カラム情報
df.describe() # 統計情報
# Excelへの書き出し
df.to_excel('output.xlsx', index=False)
Excelファイルのワークフロー
重要: 計算値のハードコードではなく数式を使用すること
Pythonで値を計算してハードコードするのではなく、常にExcelの数式を使用すること。 これにより、スプレッドシートが動的に更新可能な状態を維持できます。
❌ 誤った例 — 計算値のハードコード
# 悪い例: Pythonで計算した結果をハードコード
total = df['Sales'].sum()
sheet['B10'] = total # 5000 をハードコード
# 悪い例: Pythonで成長率を計算
growth = (df.iloc[-1]['Revenue'] - df.iloc[0]['Revenue']) / df.iloc[0]['Revenue']
sheet['C5'] = growth # 0.15 をハードコード
# 悪い例: Pythonで平均を計算
avg = sum(values) / len(values)
sheet['D20'] = avg # 42.5 をハードコード
✅ 正しい例 — Excelの数式を使用
# 良い例: ExcelにSUMを計算させる
sheet['B10'] = '=SUM(B2:B9)'
# 良い例: 成長率をExcel数式で表現
sheet['C5'] = '=(C4-C2)/C2'
# 良い例: Excel関数で平均を計算
sheet['D20'] = '=AVERAGE(D2:D19)'
合計・パーセンテージ・比率・差分など、すべての計算にこのルールが適用されます。 元データが変更された際にスプレッドシートが自動再計算できる状態を維持してください。
標準的なワークフロー
- ツールの選択: データ処理にはpandas、数式・書式設定にはopenpyxl
- 作成/読み込み: 新規ワークブックの作成、または既存ファイルの読み込み
- 編集: データ・数式・書式の追加と修正
- 保存: ファイルへの書き出し
- 数式の再計算(数式を使用する場合は必須):
scripts/recalc.pyスクリプトを使用python scripts/recalc.py output.xlsx - エラーの確認と修正:
- スクリプトはエラーの詳細をJSON形式で返す
statusがerrors_foundの場合は、error_summaryで該当するエラーの種類と場所を確認する- 特定されたエラーを修正し、再度再計算を実行する
- 主なエラーの種類:
#REF!: 無効なセル参照#DIV/0!: ゼロ除算#VALUE!: 数式に不正なデータ型#NAME?: 認識できない数式名
新規Excelファイルの作成
# 数式と書式設定にはopenpyxlを使用
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
sheet = wb.active
# データの追加
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
sheet.append(['Row', 'of', 'data'])
# 数式の追加
sheet['B2'] = '=SUM(A1:A10)'
# 書式設定
sheet['A1'].font = Font(bold=True, color='FF0000')
sheet['A1'].fill = PatternFill('solid', start_color='FFFF00')
sheet['A1'].alignment = Alignment(horizontal='center')
# 列幅の設定
sheet.column_dimensions['A'].width = 20
wb.save('output.xlsx')
既存Excelファイルの編集
# 数式と書式を保持するためopenpyxlを使用
from openpyxl import load_workbook
# 既存ファイルの読み込み
wb = load_workbook('existing.xlsx')
sheet = wb.active # または wb['SheetName'] で特定シートを指定
# 複数シートの処理
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
print(f"Sheet: {sheet_name}")
# セルの編集
sheet['A1'] = 'New Value'
sheet.insert_rows(2) # 2行目に行を挿入
sheet.delete_cols(3) # 3列目を削除
# 新規シートの追加
new_sheet = wb.create_sheet('NewSheet')
new_sheet['A1'] = 'Data'
wb.save('modified.xlsx')
数式の再計算
openpyxlで作成・編集したExcelファイルには、数式が文字列として格納されており、計算済みの値は含まれていません。
提供されている scripts/recalc.py スクリプトを使用して数式を再計算してください:
python scripts/recalc.py <excel_file> [timeout_seconds]
実行例:
python scripts/recalc.py output.xlsx 30
このスクリプトは以下を実行します:
- 初回実行時にLibreOfficeマクロを自動セットアップ
- 全シートのすべての数式を再計算
- 全セルをスキャンしてExcelエラー(#REF!、#DIV/0! 等)を検出
- エラーの場所と件数を含む詳細なJSONを返却
- LinuxおよびmacOSの両方で動作
数式の検証チェックリスト
数式が正しく機能していることを確認するための簡易チェック:
必須の検証項目
- [ ] 参照先を2〜3件テスト: フルモデルを構築する前に、正しい値を参照していることを確認する
- [ ] カラムのマッピング: Excelの列が正しく対応しているか確認する(例: 64列目 = BL、BKではない)
- [ ] 行オフセット: Excelの行は1始まりであることに注意(DataFrameの5行目 = Excelの6行目)
よくある落とし穴
- [ ] NaN処理:
pd.notna()でNull値を確認する - [ ] 右端の列: 年度データは50列目以降にあることが多い
- [ ] 複数一致: 最初の一致だけでなく、すべての出現箇所を検索する
- [ ] ゼロ除算: 数式で
/を使用する前に分母を確認する(#DIV/0!) - [ ] 参照ミス: すべてのセル参照が意図したセルを指しているか確認する(#REF!)
- [ ] クロスシート参照: シートのリンクには正しい形式を使用する(例:
Sheet1!A1)
数式のテスト方針
- [ ] 小さく始める: 広範囲に適用する前に、2〜3セルで数式をテストする
- [ ] 依存関係の確認: 数式で参照しているすべてのセルが存在することを確認する
- [ ] エッジケースのテスト: ゼロ・負の数・非常に大きな値を含めてテストする
scripts/recalc.py の出力の解釈
スクリプトはエラーの詳細をJSON形式で返します:
{
"status": "success", // または "errors_found"
"total_errors": 0, // エラーの総件数
"total_formulas": 42, // ファイル内の数式の総数
"error_summary": { // エラーがある場合のみ表示
"#REF!": {
"count": 2,
"locations": ["Sheet1!B5", "Sheet1!C10"]
}
}
}
ベストプラク
原文(English)を表示
Requirements for Outputs
All Excel files
Professional Font
- Use a consistent, professional font (e.g., Arial, Times New Roman) for all deliverables unless otherwise instructed by the user
Zero Formula Errors
- Every Excel model MUST be delivered with ZERO formula errors (#REF!, #DIV/0!, #VALUE!, #N/A, #NAME?)
Preserve Existing Templates (when updating templates)
- Study and EXACTLY match existing format, style, and conventions when modifying files
- Never impose standardized formatting on files with established patterns
- Existing template conventions ALWAYS override these guidelines
Financial models
Color Coding Standards
Unless otherwise stated by the user or existing template
Industry-Standard Color Conventions
- Blue text (RGB: 0,0,255): Hardcoded inputs, and numbers users will change for scenarios
- Black text (RGB: 0,0,0): ALL formulas and calculations
- Green text (RGB: 0,128,0): Links pulling from other worksheets within same workbook
- Red text (RGB: 255,0,0): External links to other files
- Yellow background (RGB: 255,255,0): Key assumptions needing attention or cells that need to be updated
Number Formatting Standards
Required Format Rules
- Years: Format as text strings (e.g., "2024" not "2,024")
- Currency: Use $#,##0 format; ALWAYS specify units in headers ("Revenue ($mm)")
- Zeros: Use number formatting to make all zeros "-", including percentages (e.g., "$#,##0;($#,##0);-")
- Percentages: Default to 0.0% format (one decimal)
- Multiples: Format as 0.0x for valuation multiples (EV/EBITDA, P/E)
- Negative numbers: Use parentheses (123) not minus -123
Formula Construction Rules
Assumptions Placement
- Place ALL assumptions (growth rates, margins, multiples, etc.) in separate assumption cells
- Use cell references instead of hardcoded values in formulas
- Example: Use =B5*(1+$B$6) instead of =B5*1.05
Formula Error Prevention
- Verify all cell references are correct
- Check for off-by-one errors in ranges
- Ensure consistent formulas across all projection periods
- Test with edge cases (zero values, negative numbers)
- Verify no unintended circular references
Documentation Requirements for Hardcodes
- Comment or in cells beside (if end of table). Format: "Source: [System/Document], [Date], [Specific Reference], [URL if applicable]"
- Examples:
- "Source: Company 10-K, FY2024, Page 45, Revenue Note, [SEC EDGAR URL]"
- "Source: Company 10-Q, Q2 2025, Exhibit 99.1, [SEC EDGAR URL]"
- "Source: Bloomberg Terminal, 8/15/2025, AAPL US Equity"
- "Source: FactSet, 8/20/2025, Consensus Estimates Screen"
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.
Important Requirements
LibreOffice Required for Formula Recalculation: You can assume LibreOffice is installed for recalculating formula values using the scripts/recalc.py script. The script automatically configures LibreOffice on first run, including in sandboxed environments where Unix sockets are restricted (handled by scripts/office/soffice.py)
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
- Choose tool: pandas for data, openpyxl for formulas/formatting
- Create/Load: Create new workbook or load existing file
- Modify: Add/edit data, formulas, and formatting
- Save: Write to file
- Recalculate formulas (MANDATORY IF USING FORMULAS): Use the scripts/recalc.py script
python scripts/recalc.py output.xlsx - Verify and fix any errors:
- The script returns JSON with error details
- If
statusiserrors_found, checkerror_summaryfor specific error types and locations - Fix the identified errors and recalculate again
- Common errors to fix:
#REF!: Invalid cell references#DIV/0!: Division by zero#VALUE!: Wrong data type in formula#NAME?: Unrecognized formula name
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 scripts/recalc.py script to recalculate formulas:
python scripts/recalc.py <excel_file> [timeout_seconds]
Example:
python scripts/recalc.py output.xlsx 30
The script:
- Automatically sets up LibreOffice macro on first run
- Recalculates all formulas in all sheets
- Scans ALL cells for Excel errors (#REF!, #DIV/0!, etc.)
- Returns JSON with detailed error locations and counts
- Works on both Linux and macOS
Formula Verification Checklist
Quick checks to ensure formulas work correctly:
Essential Verification
- [ ] Test 2-3 sample references: Verify they pull correct values before building full model
- [ ] Column mapping: Confirm Excel columns match (e.g., column 64 = BL, not BK)
- [ ] Row offset: Remember Excel rows are 1-indexed (DataFrame row 5 = Excel row 6)
Common Pitfalls
- [ ] NaN handling: Check for null values with
pd.notna() - [ ] Far-right columns: FY data often in columns 50+
- [ ] Multiple matches: Search all occurrences, not just first
- [ ] Division by zero: Check denominators before using
/in formulas (#DIV/0!) - [ ] Wrong references: Verify all cell references point to intended cells (#REF!)
- [ ] Cross-sheet references: Use correct format (Sheet1!A1) for linking sheets
Formula Testing Strategy
- [ ] Start small: Test formulas on 2-3 cells before applying broadly
- [ ] Verify dependencies: Check all cells referenced in formulas exist
- [ ] Test edge cases: Include zero, negative, and very large values
Interpreting scripts/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
- pandas: Best for data analysis, bulk operations, and simple data export
- openpyxl: Best for complex formatting, formulas, and Excel-specific features
Working with openpyxl
- Cell indices are 1-based (row=1, column=1 refers to cell A1)
- Use
data_only=Trueto read calculated values:load_workbook('file.xlsx', data_only=True) - Warning: If opened with
data_only=Trueand saved, formulas are replaced with values and permanently lost - For large files: Use
read_only=Truefor reading orwrite_only=Truefor writing - Formulas are preserved but not evaluated - use scripts/recalc.py to update values
Working with pandas
- Specify data types to avoid inference issues:
pd.read_excel('file.xlsx', dtype={'id': str}) - For large files, read specific columns:
pd.read_excel('file.xlsx', usecols=['A', 'C', 'E']) - Handle dates properly:
pd.read_excel('file.xlsx', parse_dates=['date_column'])
Code Style Guidelines
IMPORTANT: When generating Python code for Excel operations:
- Write minimal, concise Python code without unnecessary comments
- Avoid verbose variable names and redundant operations
- Avoid unnecessary print statements
For Excel files themselves:
- Add comments to cells with complex formulas or important assumptions
- Document data sources for hardcoded values
- Include notes for key calculations and model sections
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。