diff --git a/Design/DslDefinition/DslDefinition_v2.xsd b/Design/DslDefinition/DslDefinition_v2.xsd
index a16f95e..10bd2b6 100644
--- a/Design/DslDefinition/DslDefinition_v2.xsd
+++ b/Design/DslDefinition/DslDefinition_v2.xsd
@@ -295,6 +295,7 @@
+
@@ -313,6 +314,7 @@
+
@@ -330,6 +332,13 @@
+
+
+
+
+
+
+
diff --git a/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md b/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md
new file mode 100644
index 0000000..5ad8ab0
--- /dev/null
+++ b/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md
@@ -0,0 +1,768 @@
+# Excelテンプレート対応 詳細設計(Issue #58 / 実装方針レビュー版)
+
+- 作成日: 2026-04-07
+- ステータス: **実装方針レビュー中**
+- 対象Issue: https://github.com/ssaattww/ExcelReport/issues/58
+- 設計対象: Excel形式テンプレートを DSL へ変換する機能(`Excel -> XML Template -> DSL`)
+
+## 1. Excelテンプレート対応で合意したいこと(要約)
+Issue本文(2026-04-07作成)から、以下を設計対象とする。
+
+1. Excelテンプレートを入力にして、最終的に現行DSL/生成パイプラインへ接続したい
+2. デバッグ用途として「Excel -> XML Template -> DSL -> Excel」の中間可視化を持ちたい
+3. 本番では中間XMLを省略し「Excel -> DSL(直接変換)」も可能にしたい
+4. コンポーネント定義方式は次の2案を比較検討する
+ - A案: シート単位定義(特殊シート名)
+ - B案: 名前付き範囲定義(シート内で定義)
+
+## 2. 方針
+### 2.1 段階導入(破壊的変更なし)
+- **Phase A (Debug Path)**: Excel -> XmlTemplate を実装し、変換内容を可視化
+- **Phase B (Production Path)**: Excel -> DSL 直接変換を追加
+- 既存の `DSL -> ReportGenerator` パイプラインは再利用し、既存API互換を維持する
+
+### 2.2 コンポーネント定義方式の採用(再検討)
+ユーザー提案の A/B 案を前提にしつつ、追加で C 案を含めて比較した。
+
+- **A案: シート単位定義(特殊シート名)**
+ - 利点: 実装コストが低く、抽出境界が明確、デバッグしやすい
+ - 欠点: シート数増加時に運用が冗長になる
+- **B案: 名前付き範囲定義(シート内)**
+ - 利点: 既存Excel運用に近く、シートを増やさず定義可能
+ - 欠点: 同名管理・ネスト・範囲衝突で実装複雑度が上がる
+- **C案: セルコメント/メタ情報ベース定義(追加検討)**
+ - 利点: レイアウト自由度が高い
+ - 欠点: Excel編集で壊れやすく、規約逸脱検知が難しい
+
+**採用結論(初期リリース): A案**
+- 採用理由: 「最小コストで安定導入」「変換ロジックの可観測性」「TDDで仕様固定しやすい」の3点で優位。
+- B/Cは将来拡張として残し、A案運用データを得てから再評価する。
+
+## 3. 対象範囲
+### In Scope
+- ExcelTemplate 入力モデルの追加
+- Excel -> XmlTemplate 変換器(デバッグ用途)
+- Excel -> DSL 直接変換器(本番用途)
+- シート単位コンポーネント抽出ルール
+- 変換ログ(どのセル/範囲をどのDSL要素へ写像したか)
+- 主要テスト(unit + e2e)
+
+### Out of Scope(今回)
+- 名前付き範囲ベースのコンポーネント定義(B案本実装)
+- セルコメント/メタ情報ベース定義(C案本実装)
+- GUI/CLIツールの本格追加
+- 既存DSL構文の大幅拡張
+- **グラフ作成機能(chart生成/設定DSL拡張)は今回の対象外**
+
+## 4. アーキテクチャ設計
+
+```text
+[Excel Workbook]
+ | (Phase A)
+ v
+[ExcelTemplateExtractor] -> [XmlTemplateSerializer]
+ | (Phase B bypass possible)
+ v
+[DslEmitter]
+ v
+[Existing DslParser/Layout/Renderer]
+ v
+[Excel Output]
+```
+
+### 4.1 新規コンポーネント(案)
+- `ExcelTemplate/ExcelTemplateExtractor`
+ - Excelブックを読み取り、シート/セル/スタイル/名前情報を中間モデル化
+- `ExcelTemplate/XmlTemplateSerializer`
+ - 中間モデルをXML templateとして出力(デバッグ向け)
+- `ExcelTemplate/DslEmitter`
+ - 中間モデル(またはExcel直接)からDSL文字列へ変換
+
+### 4.2 既存コンポーネントとの責務境界
+- 既存 `DSL` パーサ以降には変更を極力入れない
+- 変換層(ExcelTemplate系)で解決できる仕様はそこで閉じる
+
+## 5. DSLマッピングルール(初版)
+- シート名 `__component_` をコンポーネント定義シートとして扱う
+- 通常シートは `` に変換
+- 値セルは `cell@value` へ変換
+- 数式セルは原則 `cell@formula` へ変換する
+- C# 側で Excel 関数の計算を再実装することは本仕様の対象外とし、数式は計算済み値へ潰さず保持する
+- 最小限のスタイル属性(font/fill/numberFormat)から段階対応
+
+### 5.1 コンポーネント定義範囲(Range)の決定ルール
+初版では、コンポーネント定義シート `__component_` ごとに、次の優先順位で定義範囲を決定する。
+
+1. 明示範囲指定(最優先)
+ - Workbook DefinedName: `__component_range_`
+ - 例: `__component_range_GroupBlock` -> `__component_GroupBlock!$A$1:$C$3`
+2. 自動判定(DefinedName未指定時)
+ - 候補セル: 値/数式/挿入トリガ/書式指定/結合セルに関与するセル
+ - 候補セルの最小外接矩形を定義範囲とする
+ - trailing側(右端/下端)の完全空行・完全空列はトリミングする
+
+補足:
+- 定義範囲は必ず単一矩形とする(離散領域は不可)。
+- 明示範囲がシート名と不整合、または空矩形の場合は Error とする。
+- 自動判定で候補セルが0件の場合は Error(`EmptyComponentRange`)とする。
+
+## 6. 失敗時ポリシー
+- 未対応Excel要素を検出した場合:
+ - 変換を継続可能なら Warning として `ReportGeneratorResult.Issues` へ集約
+ - 継続不能なら Error で停止
+- どのセルが未対応だったかを座標付きでログ出力
+- 追加ポリシー(範囲/挿入):
+ - 定義範囲が不正(空矩形/複数領域/シート不一致)の場合: Error(`InvalidComponentRange`)
+ - 挿入元展開で挿入先想定範囲を超過した場合: Warning(`TemplateRangeOverflow`, `deltaRows`/`deltaCols` を記録)
+ - 結合セルが挿入境界をまたいで破壊される場合: Error(`MergedCellBoundaryViolation`)
+
+## 7. テスト戦略(TDD)
+1. Unit
+ - シート分類(通常/コンポーネント)
+ - セル値/数式/最小スタイルの抽出
+ - DslEmitterの要素生成
+2. Integration
+ - Excel -> DSL 変換結果のスナップショット比較
+3. E2E
+ - Excel -> DSL -> ReportGenerator で最終Excel生成まで確認
+
+## 8. 互換性
+- 既存公開APIは非変更
+- 既存DSL実行機能に影響なし
+- 破壊的変更は現時点では想定しない
+
+## 9. 実装前の承認結果
+- [x] 比較検討結果(A/B/C)を踏まえ、初期実装は A案で進める
+- [x] デバッグ経路(Excel -> XML Template)を同時に入れる
+- [x] 初版マッピング対象は 値/数式/最小スタイル とする
+- [x] グラフ作成機能は今回スコープ外とする
+- [x] コンポーネント定義範囲は「DefinedName明示指定 + 自動判定フォールバック」の二段構成とする
+- [x] サイズ不一致時は「クリップせず展開 + overflow Warning」とする
+- [x] 挿入先書式は任意(mustではない)とし、3x3外枠+中央useのフレームは展開サイズへ追従拡張する
+- [x] 挿入先書式のoverflow補完は `styleOverflow`(`none`/`edge`)で選択可能、既定 `none` とする
+- [x] merged cell は初版では「矩形内完結のみ」とする
+- [x] 条件付き書式は初版対象外とする
+- [x] 数式セルは `cell@formula` へ正規化し、C# 側で Excel 関数計算を行わない
+- [x] 大規模テンプレートの性能閾値は当面不問とし、必要時に別途基準化する
+
+---
+
+## 10. 具体表現設計(入れ子コンポーネント / シート定義 / 挿入)
+
+### 10.1 コンポーネント定義シートの表し方
+- シート名規約: `__component_`
+- 例:
+ - `__component_Header`
+ - `__component_ItemRow`
+ - `__component_GroupBlock`
+
+このシートのセル配置を、そのまま component のレイアウト定義へ変換する。
+
+### 10.2 通常シート定義の表し方
+- コンポーネント定義シート以外は通常 `` として扱う。
+- 例: `Invoice` シートは DSL の `` へ変換。
+
+### 10.3 コンポーネント挿入の表し方(use)
+Excel側で次の記法を挿入トリガとして扱う(初版案):
+- セル値: `{{use:Header}}` -> ``
+- セル値: `{{use:Header, styleOverflow:edge}}` -> ``
+- セル値: `{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}` -> ``
+
+> 注: 文字列トリガ構文は初版の暫定仕様。将来は名前付き範囲等への置換余地あり。
+> 注: Excel側の shorthand expression(例: `@items`, `@group.Items`, `@item.Name`)は converter が emitted DSL 上で `@(root.Items)`, `@(group.Items)`, `@(item.Name)` へ正規化する。
+
+### 10.4 入れ子コンポーネント定義の例
+
+#### Excelテンプレート(概念)
+- `__component_Header`: タイトル行
+- `__component_ItemRow`: 明細1行(品名/数量/単価)
+- `__component_GroupBlock`: 見出し + `{{use:ItemRow, from:@group.Items, var:item}}` を含む
+- `Invoice`: `{{use:Header}}` の下に `{{use:GroupBlock, from:@groups, var:group}}`
+
+#### 変換後 DSL 例(設計イメージ)
+```xml
+
+
+
+
+ |
+
+
+
+
+
+ |
+ |
+ |
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+### 10.5 挿入時の座標ルール(初版)
+- `use` は「トリガセル位置」を挿入起点にする。
+- component の高さ/幅ぶん展開し、後続行は下方へシフト(既存 LayoutEngine 規約に追従)。
+- `repeat + use` は反復ごとに順次展開する。
+
+### 10.6 検証観点(例ベース)
+- 入れ子 repeat/use で scope (`group` / `item`) が衝突しないこと
+- `sheet` 直下と component 内で同名 var を使っても期待通りに解決されること
+- 展開後のセル位置が連続し、欠落・重複がないこと
+
+
+### 10.7 セル値の具体例(Markdownテーブル)
+
+#### 10.7.1 セル値トリガ -> DSL 変換例
+| Excelセル値(例) | 意味 | 変換後DSL(例) | 備考 |
+|---|---|---|---|
+| `請求書` | 固定文字列 | ` | ` | そのまま値セル |
+| `@item.Name` | 式評価値 | ` | ` | converter が DSL runtime 互換形へ正規化 |
+| `{{use:Header}}` | コンポーネント挿入 | `` | 挿入トリガ |
+| `{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}` | 反復+挿入 | `` | repeat展開 + styleOverflow |
+| `=SUM(B2:B10)` | Excel数式 | ` | ` | `cell@formula` で保持 |
+
+#### 10.7.2 入れ子構成のセル配置イメージ(Excel側)
+| シート | セル | 入力値 | 役割 |
+|---|---|---|---|
+| `__component_Header` | `A1` | `請求書` | ヘッダー定義 |
+| `__component_GroupBlock` | `A1` | `@group.Name` | グループ見出し |
+| `__component_GroupBlock` | `A2` | `{{use:ItemRow, from:@group.Items, var:item}}` | 子component反復挿入 |
+| `Invoice` | `A1` | `{{use:Header}}` | 先頭ヘッダー挿入 |
+| `Invoice` | `A3` | `{{use:GroupBlock, from:@groups, var:group}}` | グループ単位で入れ子展開 |
+
+#### 10.7.3 罫線の競合が起こるセル例
+| 位置 | 親component指定 | 子component指定 | 解決結果 |
+|---|---|---|---|
+| `Invoice!A10` の bottom | `thin` | `dashed` | 子優先で `dashed`(Warning記録) |
+| `Invoice!B10` の right | `medium` | 未指定 | 親の `medium` を継承 |
+| `Invoice!C10` の top | 未指定 | `thin` | 子の `thin` を採用 |
+| `Invoice!D10` の left | `thin` | `thin` | 同値のためWarningなし |
+
+
+### 10.8 Excelセル座標と一致する表現(セルマトリクス)
+
+#### 10.8.1 挿入先シート(入力テンプレート)
+| Row\Col | A | B | C |
+|---|---|---|---|
+| 1 | `{{use:Header}}` | | |
+| 2 | | | |
+| 3 | | | |
+| 4 | | `{{use:GroupBlock, from:@groups, var:group}}` | |
+| 5 | | | |
+
+#### 10.8.2 挿入元 `__component_GroupBlock` シート(3x3、入力テンプレート)
+| Row\Col | A | B | C |
+|---|---|---|---|
+| 1 | `@group.Name` | | |
+| 2 | `{{use:ItemRow, from:@group.Items, var:item}}` | | |
+| 3 | | | |
+
+#### 10.8.3 挿入先セル値のSVG(表示値ベース)
+
+
+注記:
+- `use` セル周辺に描かれている罫線は「テンプレートで定義されている場合の例」であり、必須要件ではない。
+- 挿入先書式が未定義でも `use` 展開は有効で、最終書式は 10.9/11章のルールで決定する。
+
+#### 10.8.4 挿入元セル値のSVG(表示値ベース)
+
+
+注:
+- 10.8.3/10.8.4 のSVGは、実運用のExcelTemplate見た目に合わせるため、説明用の背景色強調は行わない。
+- 挿入アンカーや有効範囲の意味づけは本文・表で説明し、セル塗り分けには反映しない。
+- ただしテンプレートで事前定義する罫線(実線/破線)は、入力側SVGにも反映する。
+- 本節の `GroupBlock` 定義範囲は `A1:C3` を採用する。周辺グリッドはシート表示であり、component 有効幅には含めない。
+
+#### 10.8.5 書式説明(Markdownテーブル)
+| 範囲/セル | 意味 | 備考 |
+|---|---|---|
+| 挿入先 `A3:C5` | 3x3 の親フレーム | 中央 `B4` が `use` アンカー |
+| 挿入先 `A1` | `{{use:Header}}` | ヘッダー挿入トリガ |
+| 挿入先 `A1:C1` | 例: 挿入先上辺の書式シード | 必須ではない(未設定でも展開可) |
+| 挿入元 `A1:C3` | `GroupBlock` の定義範囲 | 行3列3。`repeat` 展開後の高さは item 件数で増加 |
+| 挿入元 `A1` | `@group.Name` | グループ見出し |
+| 挿入元 `A2` | `{{use:ItemRow, from:@group.Items, var:item}}` | 子コンポーネント挿入 |
+
+使用データ(C# class 定義):
+`repeat + use` で挿入されるデータモデルは、初版の設計例として以下を基準にする。
+
+```csharp
+public sealed class InvoiceData
+{
+ public string Title { get; init; } = string.Empty;
+ public IReadOnlyList Groups { get; init; } = Array.Empty();
+}
+
+public sealed class GroupData
+{
+ public string Name { get; init; } = string.Empty;
+ public IReadOnlyList Items { get; init; } = Array.Empty();
+}
+
+public sealed class ItemData
+{
+ public string Name { get; init; } = string.Empty;
+ public int Qty { get; init; }
+ public decimal Price { get; init; }
+}
+```
+
+サンプル入力(C#):
+```csharp
+var data = new InvoiceData
+{
+ Title = "請求書",
+ Groups =
+ [
+ new GroupData
+ {
+ Name = "機械部品",
+ Items =
+ [
+ new ItemData { Name = "Bolt", Qty = 12, Price = 35m },
+ new ItemData { Name = "Nut", Qty = 12, Price = 18m },
+ new ItemData { Name = "Washer", Qty = 12, Price = 9m }
+ ]
+ },
+ new GroupData
+ {
+ Name = "電材",
+ Items = [ new ItemData { Name = "Cable", Qty = 3, Price = 980m } ]
+ }
+ ]
+};
+```
+
+#### 10.8.8 C#データ展開後の挿入元(`GroupBlock` インスタンス)SVG
+以下は本節のサンプルデータを `GroupBlock` 単位へ展開したときの、挿入元インスタンスの表示値イメージである。
+
+
+
+#### 10.8.9 C#データ展開後セル値のSVG(`Invoice` 出力イメージ)
+以下は本節のサンプルデータを `Invoice` シートへ挿入した出力イメージである。`Header` は `A1:F1` へ拡張し、`A3:C5` の 3x3 親フレームは `@groups` の連続展開結果をまとめて囲むため、最終的に `A3:E10` へ拡張される。`GroupBlock` 実体は 1件目が `B4:D7`、2件目が `B8:D9` に配置される。
+
+
+
+#### 10.8.10 Header拡張と3x3中央useの状態整理
+| 項目 | 入力(テンプレート) | 出力(展開後) |
+|---|---|---|
+| Header | `A1:C1` に `{{use:Header}}`、`styleOverflow=edge` | `A1:F1` まで外枠を拡張 |
+| GroupBlock repeat | `A3:C5` 外枠、中央 `B4` に `{{use:GroupBlock,...}}` | 親外枠は連続展開全体をまとめて `A3:E10` へ拡張する |
+| 1件目 GroupBlock | `repeat` の1件目 | `B4:D7` が挿入元実体。外周のみ罫線を持ち、`B7:D7` のみ下破線 |
+| 2件目 GroupBlock | `repeat` の2件目 | `B8:D9` が挿入元実体。上辺は 1件目の `B7:D7` を共有境界として使い、自身は `B9:D9` の下破線を持つ |
+| 子データ列 | 値が2列でも可 | 有効幅 `W=3`(値2列+書式1列)なら外枠幅は `W+2=5` 列(`A:E`) |
+
+注:
+- もし子の有効幅が本当に `W=2` なら、展開後外枠は `A3:D10`(4列)になる。
+- 「2列の値」と「コンポーネント有効幅」は同義ではない。幅判定は 10.10 の定義範囲で決まる。
+
+### 10.9 サイズ不一致時の挿入ルール(挿入元 > 挿入先想定範囲)
+「挿入元 component が複数行/複数列」「挿入先 component / sheet 側の想定定義範囲が小さい」のようなサイズ不一致を、行・列の両方向で明示的に扱う。
+
+1. 挿入先の事前定義範囲は **クリップ境界ではなくアンカー情報** とみなす。
+2. 挿入先の書式指定は **任意**(mustではない)。
+ - 書式未指定でも `use` 展開は有効。
+ - 書式指定がある場合のみ、11章の合成ルールで最終書式を決定する。
+3. `use` は挿入元 component の実サイズ(高さ/幅)まで必ず展開し、途中で切り詰めない。
+4. 挿入先の事前定義範囲を超えたセル(overflow行/overflow列)は、挿入元 component 側の書式決定ルール(11章)をそのまま適用する。
+5. overflow により既存セルが押し下げ/押し広げされる場合、既存セル値・既存書式・結合状態は相対位置を保ってシフトする。
+6. 挿入先想定範囲より大きい展開が発生した場合、`Warning`(種別: `TemplateRangeOverflow`)を記録し、座標/シート名/挿入元component名/`deltaRows`/`deltaCols` を出力する。
+7. 結合セルが挿入境界をまたいで壊れる場合は `Error` とし、当該挿入を停止する(自動補正しない)。
+
+#### 10.9.1 挿入先外枠の追従拡張ルール(3x3 + 中央useケース)
+挿入先側で `use` を囲む外枠(例: 3x3範囲の外枠 + 中央セルが `use`)を定義している場合、展開後は次で外枠を再計算する。
+
+- 前提:
+ - 初期外枠矩形を `R0`
+ - `use` アンカーセルを `A`
+ - `R0` 内でのアンカー余白を `topMargin/bottomMargin/leftMargin/rightMargin`
+ - 挿入元展開サイズを `H x W`
+ - `repeat` を含む場合の `H/W` は、`use` 起点で fully expand された結果全体の外接矩形サイズとする
+- 展開後外枠:
+ - `rowStart = A.row - topMargin`
+ - `rowEnd = A.row + (H - 1) + bottomMargin`
+ - `colStart = A.col - leftMargin`
+ - `colEnd = A.col + (W - 1) + rightMargin`
+- 結果:
+ - 3x3で中央use(四辺余白=1)の場合、子component展開範囲を四辺1セルぶん拡張した外枠になる。
+ - 行方向だけでなく列方向にも同じルールを適用する。
+ - `repeat` が縦方向に 2 件連続展開される場合、`H` は各インスタンス高の合計、`W` はインスタンス幅の最大値とする。
+ - 本節の `GroupBlock` 例では `H=6`、`W=3` なので、`A3:C5` の親フレームは `A3:E10` へ拡張される。
+ - 現行の `use` 展開はアンカー起点で右方向 / 下方向へ成長するモデルとし、left/up 側の負方向 overflow は発生させない。
+
+#### 10.9.2 挿入先書式の overflow 拡張ポリシー(`styleOverflow`)
+「挿入先で定義した書式を、子展開で増えた領域にも伸ばすか」を `use` 単位で選択可能にする。
+
+- 追加属性(`use`):
+ - `styleOverflow="none|edge"`
+ - 既定値は `none`(後方互換優先)
+- 例:
+
+```xml
+
+
+
+
+
+
+```
+
+- モード定義:
+ - `none`: 挿入先書式は拡張しない。増分領域は挿入元コンポーネント側書式のみで決定する。
+ - `edge`: 増分領域に対し、現行レイアウトモデルで実際に増える trailing edge(右辺 / 下辺)を基準に書式をコピーする。
+
+- `edge` の決定ルール:
+ 1. 右方向に `deltaCols > 0` の場合、右辺基準列 `baseCol = originalColEnd` を取る。
+ 2. 下方向に `deltaRows > 0` の場合、下辺基準行 `baseRow = originalRowEnd` を取る。
+ 3. 右辺 / 下辺の辺拡張では、基準辺セルに書式がある場合のみ、増分領域へ同一書式をコピーする。
+ 4. 右下角領域が同時に増える場合、元範囲の右下角セルを書式基準にする。
+ 5. 基準辺または基準角が未設定なら、その行 / 列 / 角にはコピーしない。
+ 6. コピー後も競合は 11章ルール(辺単位優先順位)で解決する。
+ 7. left / up 側の負方向 overflow は現行 `use` レイアウトモデルでは発生しないため、本版の対象外とする。
+
+- 3x3 + 中央`use` + 4列子component overflow ケースの具体化:
+ - `A1:C1` が書式設定され、`styleOverflow=edge` の場合: `D1` へ拡張される。
+ - `A1:C1` が書式設定され、`styleOverflow=none` の場合: `D1` へは拡張されない。
+ - `A1:B1` のみ書式設定され、`styleOverflow=edge` の場合: 右辺基準 `C1` が未設定のため `D1` は拡張されない。
+ - 同じ考え方で、`A3:A5` が書式設定され、下方向に `deltaRows > 0` の場合は `A6` 以降へ下辺基準で拡張する。
+
+#### 10.9.3 書式 overflow のSVG比較(3x3 -> 4列子component)
+
+
+#### 10.9.4 書式 overflow の期待結果(Markdownテーブル)
+| ケース | 入力書式シード | 設定 | 増分方向 | 期待結果 |
+|---|---|---|---|---|
+| Case 1 | `A1:C1` | `styleOverflow=none` | 右 | `D1` へは拡張しない(未設定) |
+| Case 2 | `A1:C1` | `styleOverflow=edge` | 右 | `C1` を基準に `D1` へ拡張する |
+| Case 3 | `A1:B1` | `styleOverflow=edge` | 右 | `C1` が未設定なので `D1` へは拡張しない |
+| Case 4 | `A3:A5` | `styleOverflow=edge` | 下 | `A5` を基準に `A6` 以降へ拡張する |
+| Case 5 | `B2:D4` | `styleOverflow=edge` | 右下角 | 元範囲の右下角 `D4` を基準に角領域へ拡張する |
+
+補足:
+- `A1` は `Header` component 由来の固定値(`請求書`)。
+- left / up 側の負方向 overflow は、現行 `use` 展開モデルでは対象外である。
+- 10.8.9 のSVGでは、`@groups` の2件を連続展開した結果を示す。
+- SVGの線種は 11章ルールに対応する。
+ - 実線: 親component外枠、または挿入元実体の top/left/right
+ - 破線: 挿入元実体の bottom
+
+### 10.10 コンポーネント定義範囲の具体例
+#### 10.10.1 明示範囲指定
+- 定義名: `__component_range_GroupBlock`
+- 参照先: `__component_GroupBlock!$A$1:$C$3`
+- 挙動: この矩形外のセルはコンポーネント抽出対象外とする。
+
+#### 10.10.2 自動判定時
+- 候補セルが `A1`(`@group.Name`)と `A2`(`{{use:ItemRow,...}}`)のみの場合:
+ - 初期矩形: `A1:A2`
+ - 書式指定が `C3` に存在する場合:
+ - 拡張矩形: `A1:C3`
+- この最終矩形を component 展開サイズ(高さ/幅)の基準とする。
+
+#### 10.10.3 バリデーション
+| チェック項目 | 判定 | 失敗時 |
+|---|---|---|
+| DefinedName の参照先が対象シートか | 必須 | `InvalidComponentRange` Error |
+| 範囲が単一矩形か | 必須 | `InvalidComponentRange` Error |
+| 範囲内に有効セルが1つ以上あるか | 必須 | `EmptyComponentRange` Error |
+| 自動判定で overflow が発生したか | 任意記録 | `TemplateRangeOverflow` Warning |
+
+
+## 11. セル書式方針(特に罫線)
+
+### 11.1 基本方針
+- 値/数式だけでなく、セル書式(font/fill/numberFormat/border)も抽出対象にする。
+- ただし初期段階では「既存StyleResolver/Rendererの表現可能範囲」に正規化して取り込む。
+
+### 11.2 罫線の取り扱い原則
+入れ子 component 展開時の見た目崩れを防ぐため、次の優先順位で罫線を決定する。
+
+1. **セル直指定罫線(最優先)**
+2. **component 内ローカル既定罫線**
+3. **sheet 側既定罫線(最下位)**
+
+補足:
+- 罫線は辺単位(top/right/bottom/left)で合成し、未指定辺のみ下位ルールから補完する。
+- 競合時(同じ辺に異なる指定)は上位優先とし、Warning を記録する。
+
+### 11.3 入れ子時の罫線ルール
+- 親componentと子componentの境界で、同一辺が二重定義された場合は「子component優先」。
+- `repeat + use` で連続展開される行境界は、各行の bottom/top を辺単位で解決する。
+- 列方向の境界(left/right)も同様に辺単位で解決する。
+- 同一 `repeat` から生成された sibling instance 同士が連続配置される場合、共有境界は1本だけ描画する。
+- 縦方向 repeat の共有境界では、先行 instance の `bottom` を採用し、後続 instance の `top` は重ね描きしない。
+- 横方向 repeat の共有境界では、先行 instance の `right` を採用し、後続 instance の `left` は重ね描きしない。
+- 共有境界で同優先度・異値の罫線が衝突した場合は「先行 instance の trailing edge 優先」とし、Warning を記録する。
+- 外枠を親で管理し、内側明細線を子で管理する設計を推奨。
+- 挿入先に外枠(フレーム)を定義する場合は 10.9.1 の追従拡張ルールで再配置する。
+
+### 11.4 具体例(罫線)
+
+#### 設計推奨パターン
+- `GroupBlock`(親): 外枠(top/left/right/bottom)
+- `ItemRow`(子): 明細行の下罫線(bottom)
+
+このとき:
+- 最終行以外: `ItemRow.bottom` が有効
+- グループ末尾: 親 `GroupBlock.bottom` と子 `ItemRow.bottom` が競合しうるため、子優先で解決し Warning を記録
+- `GroupBlock` が repeat で縦連結される場合: 先行 block の `bottom` を共有境界へ採用し、後続 block の `top` は描画しない
+
+### 11.5 検証ケース(実装前にテスト化予定)
+1. 親外枠 + 子内罫線の組み合わせが期待どおり描画される
+2. 入れ子 + repeat 展開で行境界の二重線/線欠けが発生しない
+3. 競合辺がある場合に Warning が `ReportGeneratorResult.Issues` に記録される
+4. 既存 border mode(outer/all)との互換が維持される
+5. 挿入元高さ > 挿入先想定行数(例: 3行 component を 1行定義領域へ挿入)でも、overflow行の書式が欠落しない
+6. 挿入元幅 > 挿入先想定列数でも、overflow列の書式が欠落しない
+7. 3x3外枠 + 中央use のテンプレートで、展開後に外枠が「子範囲+余白」で追従拡張される
+8. overflow 発生時に `TemplateRangeOverflow` Warning が座標 + `deltaRows` + `deltaCols` 付きで記録される
+9. `styleOverflow=none` で `A1:C1` 書式が `D1` へ拡張されない
+10. `styleOverflow=edge` で `A1:C1` 書式が `D1` へ拡張される
+11. `styleOverflow=edge` かつ `A1:B1` のみ書式時、`C1` 未設定のため `D1` へ拡張されない
+12. `styleOverflow=edge` で下方向に `deltaRows > 0` が発生した場合、下辺基準で overflow 行へ書式が拡張される
+13. `styleOverflow=edge` で右下角領域が増える場合、元範囲の右下角セルを基準に corner copy される
+14. 同一 `repeat` の連続 instance 境界で、先行 instance の trailing edge が共有境界として1本だけ描画される
+
+### 11.6 リスクと緩和策
+- リスク: Excel側の自由入力で罫線指定が過剰に衝突する
+ - 緩和: 競合Warningを必須化し、座標/辺情報付きでログ化
+- リスク: 入れ子深度が増えると見た目把握が難しい
+ - 緩和: デバッグ経路(Excel -> XmlTemplate)で罫線解決結果を可視化する
+
+### 11.7 非罫線書式(font/fill/numberFormat)の合成方針
+- 挿入元 component のセルが明示指定する属性は、そのまま採用する(最優先)。
+- 明示指定がない属性は `component ローカル既定 -> sheet 既定` の順で補完する。
+- `styleOverflow=none` の場合、挿入先の事前定義範囲にのみ存在する書式を overflow 行/列へ暗黙コピーしない。
+- `styleOverflow=edge` の場合、10.9.2 の辺基準ルールに従い overflow 行/列へコピーする。
+- ただし既存行を押し下げる際は、押し下げ対象セルの既存書式を保持する(破壊しない)。
+
+
+## 12. 実装前に詰めるべき懸念点(事前合意チェックリスト)
+
+以下は、実装前に合意しないと後戻りコストが高い項目。
+
+### 12.1 変換契約の厳密化
+| 懸念点 | 未合意時のリスク | 事前合意内容 |
+|---|---|---|
+| 数式セルの正規化方式(`cell@formula` vs `cell@value`) | 実装途中でDSL互換崩れ | 初版は `cell@formula` で統一する。C# 側で Excel 関数計算は行わず、計算済み値へ潰さない |
+| 空セル/空白セルの扱い | 余計なセル生成、座標ずれ | 値/数式/書式/結合/useトリガのいずれもない空セルは非出力とする。空白文字列は値セルとして出力し、`styleOverflow` の種になる書式-onlyセルは保持する |
+| 日付/数値の型解釈 | Excel表示とDSL評価の乖離 | まずは生値+numberFormatで保持し、型推論は段階導入 |
+
+### 12.2 レイアウト展開の境界条件
+| 懸念点 | 未合意時のリスク | 事前合意内容 |
+|---|---|---|
+| `use` 展開時の行/列シフト | component重なり/欠落 | 「トリガセル起点 + 高さ/幅ぶんシフト」を固定ルール化 |
+| 入れ子 `repeat + use` の展開順 | varスコープ衝突 | 親repeat1回ごとに子を完全展開する深さ優先 |
+| 挿入元サイズ > 挿入先想定範囲(行/列) | 書式欠落/罫線崩れ/既存セル上書き | 挿入先範囲はクリップしない。overflow行/列まで展開し、後続セルを相対シフト。`TemplateRangeOverflow` Warning必須 |
+| 挿入先フレーム(外枠)の追従 | 外枠が狭いまま/拡張過剰 | 10.9.1 の余白保持ルール(子範囲+余白)で外枠を再計算 |
+| merged cell 含有component | 結合領域崩れ | 初版は制限付き対応(矩形内完結のみ)で進める |
+
+### 12.3 書式・罫線の実装リスク
+| 懸念点 | 未合意時のリスク | 事前合意内容 |
+|---|---|---|
+| 挿入先書式の有無 | 「書式なしuseが無効」と誤解 | 挿入先書式は任意。未指定でも展開可、指定時のみ合成 |
+| 罫線競合時の採用規則 | 見た目不一致 | 既定ルール(子優先/辺単位/Warning)を固定 |
+| 非罫線書式のoverflow補完 | 色/フォント/表示形式の不整合 | `styleOverflow` を `none`/`edge` で明示選択し、既定は `none`。`edge` 時のみ辺基準で補完する |
+| Style重複生成 | ファイル肥大/性能低下 | StyleKeyで重複排除し、同一スタイル再利用 |
+| 条件付き書式との干渉 | 想定外の上書き | 初版は条件付き書式を非対象として進める |
+
+### 12.4 運用・性能
+| 懸念点 | 未合意時のリスク | 事前合意内容 |
+|---|---|---|
+| 大規模テンプレート(数万セル) | 変換時間増大 | 当面は性能閾値を設けず不問とする。Phase A では計測ログのみ必須とし、必要になった時点で別途基準化する |
+| 失敗時の原因追跡 | 調査コスト増 | セル座標 + シート名 + 変換段階を必ず記録 |
+| 仕様逸脱テンプレート入力 | 実行時クラッシュ | Validateフェーズを設け、Error/Warningを事前集約 |
+
+### 12.5 今回の事前合意ゴール
+- 実装開始条件として、上記表の「事前合意内容」を受け入れ条件に組み込む。
+- 合意できない項目は実装スコープから除外し、設計書へ明示する。
+
+### 12.6 実装前レビューで確認する質問
+- 現時点で未解決の確認質問はない。追加の懸念が出た場合は本節へ追記する。
+
+## 13. 実装方針
+
+### 13.1 基本方針
+- 既存の `ReportGenerator -> DslParser -> LayoutEngine -> WorksheetStateBuilder -> XlsxRenderer` は後段の安定基盤として再利用する。
+- `ExcelTemplate` 対応は前段に追加し、Excelブックを DSL へ変換した上で既存パイプラインへ流す。
+- 初版は additive change を優先し、既存の DSL 実行 API は壊さない。
+- 実装は「DSL契約の不足補完」と「ExcelTemplate変換層の追加」を分離して進める。
+
+### 13.2 既存実装との差分整理
+現行コードを前提にすると、設計を実現するには次の差分がある。
+
+1. `ExcelTemplate` 変換層がまだ存在しない
+ - `ExcelTemplateExtractor` / `XmlTemplateSerializer` / `DslEmitter` / facade API は未実装
+2. `cell@formula` 契約が DSL/XSD/AST に未反映
+ - 現行実装は `cell@value=\"=...\"` を数式扱いしているため、`cell@formula` を受ける拡張が必要
+3. `use@styleOverflow` 契約が DSL/XSD/AST/LayoutEngine に未反映
+ - 右/下 trailing edge 拡張ルールを runtime へ追加する必要がある
+4. ExcelTemplate 固有の validation / issue 種別が未実装
+ - `InvalidComponentRange` / `EmptyComponentRange` / `TemplateRangeOverflow` / `MergedCellBoundaryViolation` など
+5. `repeat` は `direction` 必須のため、converter 側で明示出力する必要がある
+ - 初版の ExcelTemplate 由来 repeat は `direction="down"` を必ず出力する
+
+### 13.3 実装単位
+初版は次の単位で実装する。
+
+1. DSL契約拡張
+ - `Design/DslDefinition/DslDefinition_v2.xsd`
+ - `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd`
+ - `DslContract` の埋め込み schema 読み込み経路
+ - `CellAst` に `formula` 対応を追加
+ - `UseAst` に `styleOverflow` 対応を追加
+ - `DslParser.ValidateDsl` に no-schema mode 用の追加検証を実装
+ - `LayoutEngine` に `cell@formula` と `styleOverflow=edge` の runtime ルールを追加
+ - `IssueKind` に ExcelTemplate 関連種別を追加
+2. レイアウト runtime 補完
+ - `styleOverflow=edge` は `ExpandUse` / `ExpandRepeat` の後段で、アンカー矩形と展開後矩形の差分に対して style-onlyセルを合成する
+ - 挿入先 seed 書式は「値なしでも style を持つ `LayoutCell`」として layout plan に残す
+ - trailing edge copy は row/col/corner ごとに `LayoutCell` を生成し、競合は 11章ルールで解決する
+3. ExcelTemplate 中間モデル
+ - `ExcelTemplateWorkbook`
+ - `ExcelTemplateSheet`
+ - `ExcelTemplateCell`
+ - `ExcelTemplateStyle`
+ - `ExcelTemplateComponentRange`
+ - `ExcelTemplateIssue`
+4. ExcelTemplate 抽出・検証
+ - OpenXML から workbook/sheet/cell/style/defined name/merged cell を読む extractor
+ - シート分類、component 範囲決定、unsupported feature 検出、trigger 解析
+5. 変換出力
+ - XML debug 出力用 serializer
+ - DSL text 出力用 emitter
+6. 統合ファサード
+ - `ConvertToDsl`
+ - `ConvertToXmlTemplate`
+ - `GenerateFromExcelTemplate`
+
+### 13.4 推奨ファイル構成
+```text
+ExcelReportLib/
+ ExcelTemplate/
+ ExcelTemplateConverter.cs
+ ExcelTemplateReportGenerator.cs
+ ExcelTemplateConvertOptions.cs
+ ExcelTemplateExtractor.cs
+ ExcelTemplateValidator.cs
+ ComponentRangeResolver.cs
+ UseTriggerParser.cs
+ DslEmitter.cs
+ XmlTemplateSerializer.cs
+ Model/
+ ExcelTemplateWorkbook.cs
+ ExcelTemplateSheet.cs
+ ExcelTemplateCell.cs
+ ExcelTemplateStyle.cs
+ ExcelTemplateComponentRange.cs
+```
+
+補足:
+- `ExcelTemplateExtractor` は OpenXML 読み取りに専念する。
+- シート分類・範囲解決・unsupported validation は extractor に埋め込まず、小さな協調クラスへ分ける。
+- `ExcelTemplateReportGenerator` は `ExcelTemplateConverter + ReportGenerator` の薄い合成層に留める。
+
+### 13.5 実装順序
+1. DSL契約の不足補完
+ - `cell@formula` と `use@styleOverflow` を先に通す
+ - runtime schema は `Design/DslDefinition/DslDefinition_v2.xsd` と test fixture の両方を更新する
+ - `ValidateDsl` で schema validation 無効時の補完検証も追加する
+ - ここを先に済ませないと、ExcelTemplate 変換器が正しい DSL を吐けない
+2. レイアウト runtime 補完
+ - `styleOverflow=edge` は `LayoutEngine` 内の post-expand 処理として追加する
+ - style-only seed cell を layout plan に保持できることを先に固定する
+3. ExcelTemplate 中間モデルと extractor
+ - 値/数式/最小スタイル/defined name/merged cell を読む
+ - 初版対象外機能は validation で Warning/Error 化する
+4. component 範囲解決と trigger 解析
+ - `__component_` 判定
+ - `__component_range_` 解決
+ - `{{use:...}}` / `repeat + use` の解析
+ - repeat は必ず `direction="down"` を明示出力する
+5. DslEmitter / XmlTemplateSerializer
+ - 中間モデルから debug XML と DSL text を生成する
+6. facade API と E2E 接続
+ - ExcelTemplate 入力から最終 Excel 生成までを 1 API で呼べるようにする
+
+### 13.6 API 方針
+- 既存 `ReportGenerator` は DSL 専用のまま維持する。
+- ExcelTemplate 入口は新規 API として追加する。
+
+想定シグネチャ例:
+```csharp
+public sealed class ExcelTemplateConversionResult
+{
+ public string Text { get; }
+ public IReadOnlyList Issues { get; }
+}
+
+public sealed class ExcelTemplateConverter
+{
+ public ExcelTemplateConversionResult ConvertToDsl(string xlsxPath, ExcelTemplateConvertOptions? options = null);
+ public ExcelTemplateConversionResult ConvertToXmlTemplate(string xlsxPath, ExcelTemplateConvertOptions? options = null);
+}
+
+public sealed class ExcelTemplateReportGenerator
+{
+ public ReportGeneratorResult GenerateFromExcelTemplate(
+ string xlsxPath,
+ object? data,
+ ExcelTemplateGenerateOptions? options = null,
+ CancellationToken cancellationToken = default);
+}
+```
+
+方針:
+- 最初は `string xlsxPath` を主入口にする。stream overload は必要になった時点で追加する。
+- debug 用に「生成 DSL / XML を返す API」を分離し、最終生成 API に詰め込みすぎない。
+- conversion-only API でも `Issues` を返し、座標付き Warning/Error を失わない。
+
+### 13.7 テスト戦略
+1. Unit
+ - `cell@formula` / `styleOverflow` の parser/runtime
+ - `UseTriggerParser`
+ - `ComponentRangeResolver`
+ - `repeat@direction="down"` 明示出力
+ - extractor の値/数式/スタイル/defined name/merged cell 抽出
+ - 既存後方互換: `cell@value="=..."` が従来どおり数式として動くこと
+2. Integration
+ - xlsx -> xml template snapshot
+ - xlsx -> dsl snapshot
+3. E2E
+ - xlsx template -> dsl -> final xlsx
+ - `GroupBlock` / `ItemRow` の repeat/use 展開
+ - `styleOverflow=edge`
+ - `cell@formula`
+ - merged cell 制約 violation
+
+### 13.8 実装時のガードレール
+- 初版対象外の条件付き書式は extractor/validator で明示的に検出し、silent ignore しない。
+- merged cell は component 定義範囲内で完結している場合だけ許可し、境界跨ぎは Error にする。
+- 数式は値に潰さず保持し、C# 側で Excel 関数計算はしない。
+- `styleOverflow=edge` は現行レイアウトモデルに合わせ、right/down/right-down corner のみ対応する。
+- schema validation を無効化しても契約逸脱を見逃さないよう、`ValidateDsl` で `formula/value` 競合と `styleOverflow` 値を検証する。
+- 既存 `ReportGenerator` の公開挙動を変える変更は避け、必要なら新規 API で閉じる。
+
+### 13.9 完了条件
+- ExcelTemplate から DSL 変換が unit/integration で固定されている
+- ExcelTemplate から最終 Excel 生成まで E2E で通る
+- Issue / logger に座標付き原因が残る
+- 初版対象外機能は validation で検知できる
+- 設計書と実装の契約差分が解消されている
diff --git a/Design/ExcelTemplate/assets/cell-style-state-example.svg b/Design/ExcelTemplate/assets/cell-style-state-example.svg
new file mode 100644
index 0000000..30b8af2
--- /dev/null
+++ b/Design/ExcelTemplate/assets/cell-style-state-example.svg
@@ -0,0 +1,76 @@
+
diff --git a/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg b/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg
new file mode 100644
index 0000000..5c68755
--- /dev/null
+++ b/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg
@@ -0,0 +1,75 @@
+
diff --git a/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg b/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg
new file mode 100644
index 0000000..795b236
--- /dev/null
+++ b/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg
@@ -0,0 +1,73 @@
+
diff --git a/Design/ExcelTemplate/assets/insert-source-cell-values.svg b/Design/ExcelTemplate/assets/insert-source-cell-values.svg
new file mode 100644
index 0000000..e6c77cb
--- /dev/null
+++ b/Design/ExcelTemplate/assets/insert-source-cell-values.svg
@@ -0,0 +1,52 @@
+
diff --git a/Design/ExcelTemplate/assets/insert-target-cell-values.svg b/Design/ExcelTemplate/assets/insert-target-cell-values.svg
new file mode 100644
index 0000000..43a44bc
--- /dev/null
+++ b/Design/ExcelTemplate/assets/insert-target-cell-values.svg
@@ -0,0 +1,67 @@
+
diff --git a/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg b/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg
new file mode 100644
index 0000000..c203c5d
--- /dev/null
+++ b/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg
@@ -0,0 +1,79 @@
+
diff --git a/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs b/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs
new file mode 100644
index 0000000..94782ba
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs
@@ -0,0 +1,77 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class DslEmitterTests
+{
+ ///
+ /// Verifies that emitter writes DSL text with workbook, component, and sheet structure.
+ ///
+ [Fact]
+ public void Emit_WritesDslTextForWorkbookComponentsAndSheets()
+ {
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook());
+ var emitter = new DslEmitter();
+
+ var text = emitter.Emit(contract);
+
+ Assert.StartsWith("", text, StringComparison.Ordinal);
+ Assert.Contains("", text, StringComparison.Ordinal);
+ Assert.Contains("", text, StringComparison.Ordinal);
+ Assert.Contains("", text, StringComparison.Ordinal);
+
+ var parseResult = DslParser.ParseFromText(
+ text,
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+
+ ///
+ /// Verifies that emitter preserves formula, explicit styleOverflow, and repeat direction in DSL text.
+ ///
+ [Fact]
+ public void Emit_PreservesFormulaStyleOverflowAndDirection()
+ {
+ var contract = new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputContract(
+ components:
+ [
+ new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputComponent(
+ "Header",
+ "__component_Header",
+ "A1:B2",
+ isRangeResolved: true,
+ items:
+ [
+ new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputCell("A1", 1, 1, null, null, "SUM(C1:C3)"),
+ new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputRepeatUse("A2", 2, 1, null, "ItemRow", "@items", "item", "down", "edge"),
+ ]),
+ ],
+ sheets:
+ [
+ new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputSheet(
+ "Invoice",
+ [
+ new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputUse("A1", 1, 1, null, "Header", "edge"),
+ ]),
+ ]);
+ var emitter = new DslEmitter();
+
+ var text = emitter.Emit(contract);
+
+ Assert.Contains("formula=\"SUM(C1:C3)\"", text, StringComparison.Ordinal);
+ Assert.Contains("styleOverflow=\"edge\"", text, StringComparison.Ordinal);
+ Assert.Contains("direction=\"down\"", text, StringComparison.Ordinal);
+
+ var parseResult = DslParser.ParseFromText(
+ text,
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs b/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs
index d4a9dff..1a21f2b 100644
--- a/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs
+++ b/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs
@@ -254,6 +254,44 @@ public void ParseFromText_CellValueElement_WithSchemaValidation_Succeeds()
issue => issue.Kind == IssueKind.SchemaViolation && issue.Severity == IssueSeverity.Fatal);
}
+ ///
+ /// Verifies that parse cell formula and use style overflow with schema validation succeeds.
+ ///
+ [Fact]
+ public void ParseFromText_CellFormulaAndUseStyleOverflow_WithSchemaValidation_Succeeds()
+ {
+ var result = DslParser.ParseFromText(
+ """
+
+
+
+ |
+
+
+
+ |
+
+
+
+ """,
+ new DslParserOptions
+ {
+ EnableSchemaValidation = true,
+ });
+
+ Assert.False(result.HasFatal);
+ var root = Assert.IsType(result.Root);
+ var sheet = Assert.Single(root.Sheets);
+ var cell = Assert.IsType(sheet.Children.Values.First());
+ var use = Assert.IsType(sheet.Children.Values.Last());
+
+ Assert.Equal("SUM(B2:B10)", cell.FormulaRaw);
+ Assert.Equal("edge", use.StyleOverflow);
+ Assert.DoesNotContain(
+ result.Issues,
+ issue => issue.Kind == IssueKind.SchemaViolation && issue.Severity == IssueSeverity.Fatal);
+ }
+
///
/// Verifies that static chart bounds validation checks Excel limits even when sheet rows and cols are omitted.
///
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs
new file mode 100644
index 0000000..c7efdb5
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs
@@ -0,0 +1,152 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class ExcelTemplateComponentRangeResolverTests
+{
+ ///
+ /// Verifies that explicit defined name range takes precedence.
+ ///
+ [Fact]
+ public void Resolve_DefinedName_UsesExplicitRange()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Header",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "Title", null, null),
+ ]),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$C$3",
+ });
+
+ var resolver = new ExcelTemplateComponentRangeResolver();
+
+ var result = resolver.Resolve(workbook);
+
+ var range = Assert.Single(result.Ranges);
+ Assert.Equal("Header", range.ComponentName);
+ Assert.Equal("__component_Header", range.SheetName);
+ Assert.Equal("A1:C3", range.Reference);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that auto detection uses cells and merged ranges.
+ ///
+ [Fact]
+ public void Resolve_WithoutDefinedName_UsesAutoDetectedBoundingBox()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_GroupBlock",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "Header", null, null),
+ new ExcelTemplateCell("C2", 2, 3, null, "SUM(A1:A1)", null),
+ ],
+ mergedRanges: ["A4:B4"]),
+ ]);
+
+ var resolver = new ExcelTemplateComponentRangeResolver();
+
+ var result = resolver.Resolve(workbook);
+
+ var range = Assert.Single(result.Ranges);
+ Assert.Equal("GroupBlock", range.ComponentName);
+ Assert.Equal("A1:C4", range.Reference);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that empty component candidates return error.
+ ///
+ [Fact]
+ public void Resolve_EmptyComponentCandidates_ReturnsError()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet("__component_Empty"),
+ ]);
+
+ var resolver = new ExcelTemplateComponentRangeResolver();
+
+ var result = resolver.Resolve(workbook);
+
+ Assert.Empty(result.Ranges);
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.EmptyComponentRange);
+ }
+
+ ///
+ /// Verifies that defined name pointing to another sheet returns invalid component range error.
+ ///
+ [Fact]
+ public void Resolve_DefinedNamePointingOtherSheet_ReturnsError()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Header",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "Title", null, null),
+ ]),
+ new ExcelTemplateSheet("Summary"),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'Summary'!$A$1:$B$2",
+ });
+
+ var resolver = new ExcelTemplateComponentRangeResolver();
+
+ var result = resolver.Resolve(workbook);
+
+ Assert.Empty(result.Ranges);
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.InvalidComponentRange);
+ }
+
+ ///
+ /// Verifies that explicit range without candidates returns empty component range error.
+ ///
+ [Fact]
+ public void Resolve_DefinedNameWithoutCandidates_ReturnsEmptyComponentRange()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet("__component_Header"),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$B$2",
+ });
+
+ var resolver = new ExcelTemplateComponentRangeResolver();
+
+ var result = resolver.Resolve(workbook);
+
+ Assert.Empty(result.Ranges);
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.EmptyComponentRange);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs
new file mode 100644
index 0000000..5395758
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs
@@ -0,0 +1,117 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides integration tests for .
+///
+public sealed class ExcelTemplateConverterTests
+{
+ ///
+ /// Verifies that converter returns DSL text and no issues for a valid workbook.
+ ///
+ [Fact]
+ public void ConvertToDsl_ValidWorkbook_ReturnsDslText()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateStandardWorkbookFile();
+
+ try
+ {
+ var converter = new ExcelTemplateConverter();
+
+ var result = converter.ConvertToDsl(xlsxPath);
+
+ Assert.Contains("", result.Text, StringComparison.Ordinal);
+ Assert.Empty(result.Issues);
+
+ var parseResult = DslParser.ParseFromText(
+ result.Text,
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that converter aggregates validation issues while still returning DSL-compatible XML text.
+ ///
+ [Fact]
+ public void ConvertToXmlTemplate_InvalidWorkbook_ReturnsTextAndAggregatedIssues()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateIssueWorkbookFile();
+
+ try
+ {
+ var converter = new ExcelTemplateConverter();
+
+ var result = converter.ConvertToXmlTemplate(xlsxPath);
+
+ Assert.Contains("", result.Text, StringComparison.Ordinal);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.InvalidAttributeValue);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that a corrupt workbook is reported as a fatal load issue instead of escaping as an exception.
+ ///
+ [Fact]
+ public void ConvertToDsl_CorruptWorkbook_ReturnsFatalLoadIssue()
+ {
+ var xlsxPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx");
+ File.WriteAllText(xlsxPath, "not-an-xlsx");
+
+ try
+ {
+ var converter = new ExcelTemplateConverter();
+
+ var result = converter.ConvertToDsl(xlsxPath);
+
+ Assert.Equal(string.Empty, result.Text);
+ var issue = Assert.Single(result.Issues);
+ Assert.Equal(IssueSeverity.Fatal, issue.Severity);
+ Assert.Equal(IssueKind.LoadFile, issue.Kind);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that disabling schema validation still keeps non-schema DSL contract validation.
+ ///
+ [Fact]
+ public void ConvertToDsl_WhenSchemaValidationDisabled_StillValidatesDslContracts()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateUndefinedComponentWorkbookFile();
+
+ try
+ {
+ var converter = new ExcelTemplateConverter();
+
+ var result = converter.ConvertToDsl(
+ xlsxPath,
+ new ExcelTemplateConvertOptions { EnableSchemaValidation = false });
+
+ Assert.Contains("", result.Text, StringComparison.Ordinal);
+ Assert.True(
+ result.Issues.Count(issue => issue.Kind == IssueKind.UndefinedComponent) >= 2,
+ "UndefinedComponent issues should include validator + parser results.");
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs
new file mode 100644
index 0000000..62e341c
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs
@@ -0,0 +1,178 @@
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+using ExcelReportLib.Renderer;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides end-to-end tests for ExcelTemplate conversion and rendering.
+///
+public sealed class ExcelTemplateEndToEndTests
+{
+ ///
+ /// Verifies that nested GroupBlock and ItemRow templates are converted into DSL-compatible text.
+ ///
+ [Fact]
+ public void ConvertToDsl_NestedWorkbook_PreservesDslCompatibilityTokens()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateNestedReportWorkbookFile();
+
+ try
+ {
+ var converter = new ExcelTemplateConverter();
+
+ var result = converter.ConvertToDsl(xlsxPath);
+
+ Assert.DoesNotContain(result.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ Assert.Contains("styleOverflow=\"edge\"", result.Text, StringComparison.Ordinal);
+ Assert.Contains("from=\"@(root.Groups)\"", result.Text, StringComparison.Ordinal);
+ Assert.Contains("from=\"@(group.Items)\"", result.Text, StringComparison.Ordinal);
+ Assert.Contains("value=\"@(item.Name)\"", result.Text, StringComparison.Ordinal);
+ Assert.Contains("formula=\"SUM(B4:B8)\"", result.Text, StringComparison.Ordinal);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that nested GroupBlock and ItemRow templates render expected workbook content through the facade.
+ ///
+ [Fact]
+ public void GenerateFromExcelTemplate_NestedWorkbook_ProducesExpectedWorkbook()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateNestedReportWorkbookFile();
+
+ try
+ {
+ var generator = new ExcelTemplateReportGenerator();
+
+ var result = generator.GenerateFromExcelTemplate(
+ xlsxPath,
+ new
+ {
+ Groups = new[]
+ {
+ new
+ {
+ Name = "Hardware",
+ Items = new[]
+ {
+ new { Name = "Mouse", Qty = 2, Price = 1200 },
+ },
+ },
+ new
+ {
+ Name = "Wiring",
+ Items = new[]
+ {
+ new { Name = "Cable", Qty = 3, Price = 980 },
+ },
+ },
+ },
+ },
+ CreateOptions());
+
+ Assert.True(
+ result.Output is not null,
+ string.Join(Environment.NewLine, result.Issues.Select(issue => $"{issue.Severity}:{issue.Kind}:{issue.Message}")));
+ Assert.DoesNotContain(result.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+
+ using var document = OpenWorkbook(result);
+ Assert.Equal("Invoice", ReadCellValue(document, GetCell(document, "Invoice", "A1")));
+ Assert.Equal("Hardware", ReadCellValue(document, GetCell(document, "Invoice", "A3")));
+ Assert.Equal("Mouse", ReadCellValue(document, GetCell(document, "Invoice", "A4")));
+ Assert.Equal("2", ReadCellValue(document, GetCell(document, "Invoice", "B4")));
+ Assert.Equal("1200", ReadCellValue(document, GetCell(document, "Invoice", "C4")));
+ Assert.Equal("Wiring", ReadCellValue(document, GetCell(document, "Invoice", "A5")));
+ Assert.Equal("Cable", ReadCellValue(document, GetCell(document, "Invoice", "A6")));
+ Assert.Equal("SUM(B4:B8)", GetCell(document, "Invoice", "B1").CellFormula?.Text);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that negative validation cases are surfaced on the final result.
+ ///
+ [Fact]
+ public void GenerateFromExcelTemplate_WorkbookWithValidationIssues_ReturnsIssues()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateValidationIssueWorkbookFile();
+
+ try
+ {
+ var generator = new ExcelTemplateReportGenerator();
+
+ var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions());
+
+ Assert.NotNull(result.Output);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.MergedCellBoundaryViolation);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature);
+
+ using var document = OpenWorkbook(result);
+ Assert.Equal("Ready", ReadCellValue(document, GetCell(document, "Summary", "A1")));
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ private static ExcelTemplateGenerateOptions CreateOptions() =>
+ new()
+ {
+ ReportGeneratorOptions = new ReportGeneratorOptions
+ {
+ EnableSchemaValidation = false,
+ RenderOptions = new RenderOptions
+ {
+ TemplateName = "Task11",
+ DataSource = "Tests",
+ GeneratedAt = new DateTimeOffset(2026, 4, 14, 0, 0, 0, TimeSpan.Zero),
+ },
+ },
+ };
+
+ private static SpreadsheetDocument OpenWorkbook(ReportGeneratorResult result)
+ {
+ var output = Assert.IsType(result.Output);
+ output.Position = 0;
+ return SpreadsheetDocument.Open(output, false);
+ }
+
+ private static WorksheetPart GetWorksheetPart(SpreadsheetDocument document, string sheetName) =>
+ (WorksheetPart)document.WorkbookPart!.GetPartById(
+ document.WorkbookPart.Workbook.Sheets!.Elements()
+ .Single(sheet => sheet.Name!.Value == sheetName)
+ .Id!);
+
+ private static Cell GetCell(SpreadsheetDocument document, string sheetName, string reference) =>
+ GetWorksheetPart(document, sheetName)
+ .Worksheet
+ .Descendants()
+ .Single(cell => cell.CellReference!.Value == reference);
+
+ private static string ReadCellValue(SpreadsheetDocument document, Cell cell)
+ {
+ if (cell.DataType?.Value == CellValues.InlineString)
+ {
+ return cell.InlineString!.InnerText;
+ }
+
+ if (cell.DataType?.Value == CellValues.SharedString)
+ {
+ return document.WorkbookPart!.SharedStringTablePart!.SharedStringTable
+ .Elements()
+ .ElementAt(int.Parse(cell.CellValue!.Text, System.Globalization.CultureInfo.InvariantCulture))
+ .InnerText;
+ }
+
+ return cell.CellValue?.Text ?? string.Empty;
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs
new file mode 100644
index 0000000..83cf601
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs
@@ -0,0 +1,189 @@
+using System.Globalization;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class ExcelTemplateExtractorTests
+{
+ ///
+ /// Verifies that extract reads workbook sheets, cells, defined names, and merged ranges.
+ ///
+ [Fact]
+ public void Extract_ReadsWorkbookSheetsCellsDefinedNamesAndMergedRanges()
+ {
+ var xlsxPath = CreateWorkbookFile();
+
+ try
+ {
+ var extractor = new ExcelTemplateExtractor();
+
+ var workbook = extractor.Extract(xlsxPath);
+
+ Assert.Equal(2, workbook.Sheets.Count);
+ Assert.Equal("'__component_Header'!$A$1:$B$2", workbook.DefinedNames["__component_range_Header"]);
+
+ var componentSheet = workbook.Sheets.Single(sheet => sheet.Name == "__component_Header");
+ var summarySheet = workbook.Sheets.Single(sheet => sheet.Name == "Summary");
+
+ var titleCell = componentSheet.Cells.Single(cell => cell.Reference == "A1");
+ var formulaCell = componentSheet.Cells.Single(cell => cell.Reference == "B2");
+ var numericCell = summarySheet.Cells.Single(cell => cell.Reference == "C3");
+
+ Assert.Equal("Title", titleCell.Value);
+ Assert.Null(titleCell.Formula);
+ Assert.Equal("SUM(C1:C3)", formulaCell.Formula);
+ Assert.Null(formulaCell.Value);
+ Assert.Equal("42", numericCell.Value);
+ Assert.Contains("A1:B1", componentSheet.MergedRanges);
+ Assert.False(componentSheet.HasConditionalFormatting);
+ Assert.True(summarySheet.HasConditionalFormatting);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that extract missing file throws file not found.
+ ///
+ [Fact]
+ public void Extract_MissingFile_ThrowsFileNotFoundException()
+ {
+ var extractor = new ExcelTemplateExtractor();
+ var missingPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture), "missing.xlsx");
+
+ Assert.Throws(() => extractor.Extract(missingPath));
+ }
+
+ private static string CreateWorkbookFile()
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx");
+
+ using var document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
+ var workbookPart = document.AddWorkbookPart();
+ workbookPart.Workbook = new Workbook();
+
+ var sheets = workbookPart.Workbook.AppendChild(new Sheets());
+ var componentSheetPart = CreateWorksheetPart(
+ workbookPart,
+ "__component_Header",
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "Title"),
+ CreateFormulaCell("B2", "SUM(C1:C3)"),
+ ],
+ mergedRange: "A1:B1");
+ var summarySheetPart = CreateWorksheetPart(
+ workbookPart,
+ "Summary",
+ sheetId: 2U,
+ cells:
+ [
+ CreateNumberCell("C3", "42"),
+ ],
+ hasConditionalFormatting: true);
+
+ sheets.Append(
+ CreateSheet(componentSheetPart, workbookPart, "__component_Header", 1U),
+ CreateSheet(summarySheetPart, workbookPart, "Summary", 2U));
+
+ workbookPart.Workbook.DefinedNames = new DefinedNames(
+ new DefinedName
+ {
+ Name = "__component_range_Header",
+ Text = "'__component_Header'!$A$1:$B$2",
+ });
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ private static WorksheetPart CreateWorksheetPart(
+ WorkbookPart workbookPart,
+ string sheetName,
+ uint sheetId,
+ IReadOnlyList cells,
+ string? mergedRange = null,
+ bool hasConditionalFormatting = false)
+ {
+ var worksheetPart = workbookPart.AddNewPart($"rId{sheetId}");
+ var worksheet = new Worksheet();
+ var sheetData = worksheet.AppendChild(new SheetData());
+ var rows = cells
+ .GroupBy(cell => GetRowIndex(cell.CellReference?.Value ?? string.Empty))
+ .OrderBy(group => group.Key);
+
+ foreach (var rowGroup in rows)
+ {
+ var row = new Row { RowIndex = rowGroup.Key };
+ foreach (var cell in rowGroup.OrderBy(cell => cell.CellReference!.Value, StringComparer.Ordinal))
+ {
+ row.Append(cell);
+ }
+
+ sheetData.Append(row);
+ }
+
+ if (!string.IsNullOrWhiteSpace(mergedRange))
+ {
+ worksheet.Append(new MergeCells(new MergeCell { Reference = mergedRange }));
+ }
+
+ if (hasConditionalFormatting)
+ {
+ worksheet.Append(
+ new ConditionalFormatting
+ {
+ SequenceOfReferences = new ListValue { InnerText = "C3" },
+ });
+ }
+
+ worksheetPart.Worksheet = worksheet;
+ worksheetPart.Worksheet.Save();
+ return worksheetPart;
+ }
+
+ private static Sheet CreateSheet(WorksheetPart worksheetPart, WorkbookPart workbookPart, string name, uint sheetId) =>
+ new()
+ {
+ Id = workbookPart.GetIdOfPart(worksheetPart),
+ Name = name,
+ SheetId = sheetId,
+ };
+
+ private static Cell CreateInlineStringCell(string reference, string value) =>
+ new()
+ {
+ CellReference = reference,
+ DataType = CellValues.InlineString,
+ InlineString = new InlineString(new Text(value)),
+ };
+
+ private static Cell CreateFormulaCell(string reference, string formula) =>
+ new()
+ {
+ CellReference = reference,
+ CellFormula = new CellFormula(formula),
+ };
+
+ private static Cell CreateNumberCell(string reference, string value) =>
+ new()
+ {
+ CellReference = reference,
+ CellValue = new CellValue(value),
+ };
+
+ private static uint GetRowIndex(string cellReference)
+ {
+ var digits = new string(cellReference.Where(char.IsDigit).ToArray());
+ return uint.Parse(digits, CultureInfo.InvariantCulture);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs
new file mode 100644
index 0000000..537bc90
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs
@@ -0,0 +1,277 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class ExcelTemplateOutputContractBuilderTests
+{
+ ///
+ /// Verifies that the builder classifies component and sheet scopes and normalizes cells, use, and repeat-use entries.
+ ///
+ [Fact]
+ public void Build_ClassifiesScopesAndNormalizesOutputEntries()
+ {
+ var workbook = ExcelTemplateOutputContractFixture.CreateStandardWorkbook();
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ Assert.Empty(contract.Issues);
+ Assert.Equal(2, contract.Components.Count);
+ Assert.Single(contract.Sheets);
+
+ var header = contract.Components.Single(component => component.Name == "Header");
+ Assert.Equal("__component_Header", header.SourceSheetName);
+ Assert.True(header.IsRangeResolved);
+ Assert.Equal("A1:B2", header.RangeReference);
+ Assert.Equal(3, header.Items.Count);
+
+ var titleCell = Assert.IsType(header.Items[0]);
+ Assert.Equal("A1", titleCell.Reference);
+ Assert.Equal("請求書", titleCell.Value);
+ Assert.Null(titleCell.Formula);
+
+ var repeatUse = Assert.IsType(header.Items[1]);
+ Assert.Equal("A2", repeatUse.Reference);
+ Assert.Equal("ItemRow", repeatUse.ComponentName);
+ Assert.Equal("@(root.Items)", repeatUse.FromExpression);
+ Assert.Equal("item", repeatUse.VariableName);
+ Assert.Equal("down", repeatUse.Direction);
+ Assert.Null(repeatUse.StyleOverflow);
+
+ var formulaCell = Assert.IsType(header.Items[2]);
+ Assert.Equal("B2", formulaCell.Reference);
+ Assert.Null(formulaCell.Value);
+ Assert.Equal("SUM(C1:C3)", formulaCell.Formula);
+ Assert.Equal((uint)7, formulaCell.StyleIndex);
+
+ Assert.DoesNotContain(header.Items, item => item.Reference == "C3");
+
+ var invoice = Assert.Single(contract.Sheets);
+ Assert.Equal("Invoice", invoice.Name);
+ Assert.Equal(2, invoice.Items.Count);
+
+ var headerUse = Assert.IsType(invoice.Items[0]);
+ Assert.Equal("A1", headerUse.Reference);
+ Assert.Equal("Header", headerUse.ComponentName);
+ Assert.Null(headerUse.StyleOverflow);
+
+ var invoiceFormula = Assert.IsType(invoice.Items[1]);
+ Assert.Equal("B3", invoiceFormula.Reference);
+ Assert.Equal("SUM(B4:B8)", invoiceFormula.Formula);
+
+ var itemRow = contract.Components.Single(component => component.Name == "ItemRow");
+ var itemNameCell = Assert.IsType(Assert.Single(itemRow.Items));
+ Assert.Equal("@(item.Name)", itemNameCell.Value);
+ }
+
+ ///
+ /// Verifies that range resolution and validation issues are aggregated into the contract result.
+ ///
+ [Fact]
+ public void Build_AggregatesRangeResolutionAndValidationIssues()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet("__component_Empty"),
+ new ExcelTemplateSheet(
+ "Summary",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Missing", null, null),
+ ],
+ hasConditionalFormatting: true),
+ ]);
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var emptyComponent = Assert.Single(contract.Components);
+ Assert.Equal("Empty", emptyComponent.Name);
+ Assert.False(emptyComponent.IsRangeResolved);
+ Assert.Null(emptyComponent.RangeReference);
+ Assert.Empty(emptyComponent.Items);
+
+ Assert.Single(contract.Sheets);
+ var summary = Assert.Single(contract.Sheets);
+ var malformedTriggerCell = Assert.IsType(Assert.Single(summary.Items));
+ Assert.Equal("A1", malformedTriggerCell.Reference);
+ Assert.Equal("{{use:Missing", malformedTriggerCell.Value);
+
+ Assert.Contains(contract.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange);
+ Assert.Contains(contract.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature);
+ Assert.Contains(
+ contract.Issues,
+ issue => issue.Kind == IssueKind.InvalidAttributeValue
+ && issue.Message.Contains("A1", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Verifies that style-only cells inside a resolved component range remain in the normalized output.
+ ///
+ [Fact]
+ public void Build_ComponentRangeWithStyleOnlyCell_KeepsStyledEmptyCell()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Header",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "Title", null, null),
+ new ExcelTemplateCell("B1", 1, 2, null, null, new ExcelTemplateStyle(11)),
+ ]),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1",
+ });
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var header = Assert.Single(contract.Components);
+ Assert.Equal(2, header.Items.Count);
+
+ var styledCell = Assert.IsType(header.Items[1]);
+ Assert.Equal("B1", styledCell.Reference);
+ Assert.Null(styledCell.Value);
+ Assert.Null(styledCell.Formula);
+ Assert.Equal((uint)11, styledCell.StyleIndex);
+ }
+
+ ///
+ /// Verifies that styleOverflow from Excel use triggers is preserved in the output contract.
+ ///
+ [Fact]
+ public void Build_UseTriggerWithStyleOverflow_PreservesExplicitOverflow()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "Invoice",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Header, styleOverflow:edge}}", null, null),
+ new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}", null, null),
+ ]),
+ ]);
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var invoice = Assert.Single(contract.Sheets);
+ var simpleUse = Assert.IsType(invoice.Items[0]);
+ Assert.Equal("edge", simpleUse.StyleOverflow);
+
+ var repeatUse = Assert.IsType(invoice.Items[1]);
+ Assert.Equal("edge", repeatUse.StyleOverflow);
+ Assert.Equal("@(root.Items)", repeatUse.FromExpression);
+ }
+
+ ///
+ /// Verifies that simple shorthand local variables are not rewritten to root scope.
+ ///
+ [Fact]
+ public void Build_SimpleIdentifierValue_UsesLocalRepeatScopeWhenVariableExists()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_ItemRow",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "@item", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "Invoice",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:ItemRow, from:@items, var:item}}", null, null),
+ ]),
+ ]);
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var itemRow = Assert.Single(contract.Components);
+ var itemCell = Assert.IsType(Assert.Single(itemRow.Items));
+ Assert.Equal("@(item)", itemCell.Value);
+
+ var invoice = Assert.Single(contract.Sheets);
+ var repeatUse = Assert.IsType(Assert.Single(invoice.Items));
+ Assert.Equal("@(root.Items)", repeatUse.FromExpression);
+ }
+
+ ///
+ /// Verifies that repeat variable names do not leak to unrelated components.
+ ///
+ [Fact]
+ public void Build_SimpleIdentifierValue_DoesNotLeakVariableScopeAcrossComponents()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Target",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "@item", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "__component_Other",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "X", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "Invoice",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Other, from:@items, var:item}}", null, null),
+ ]),
+ ]);
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var target = contract.Components.Single(component => component.Name == "Target");
+ var targetCell = Assert.IsType(Assert.Single(target.Items));
+ Assert.Equal("@(root.Item)", targetCell.Value);
+ }
+
+ ///
+ /// Verifies that reusing one component with multiple variable names is reported as an ambiguous normalization error.
+ ///
+ [Fact]
+ public void Build_ComponentReferencedByMultipleVariables_ReportsAmbiguousNormalization()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_ItemRow",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "@item", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "Invoice",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:ItemRow, from:@items, var:item}}", null, null),
+ new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@rows, var:row}}", null, null),
+ ]),
+ ]);
+ var builder = new ExcelTemplateOutputContractBuilder();
+
+ var contract = builder.Build(workbook);
+
+ var itemRow = Assert.Single(contract.Components);
+ var itemCell = Assert.IsType(Assert.Single(itemRow.Items));
+ Assert.Equal("@(root.Item)", itemCell.Value);
+ Assert.Contains(
+ contract.Issues,
+ issue => issue.Kind == IssueKind.InvalidAttributeValue &&
+ issue.Message.Contains("multiple repeat variables", StringComparison.Ordinal));
+ }
+
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs
new file mode 100644
index 0000000..302f1e3
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs
@@ -0,0 +1,59 @@
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides reusable ExcelTemplate workbook fixtures for conversion output tests.
+///
+internal static class ExcelTemplateOutputContractFixture
+{
+ ///
+ /// Creates a workbook fixture covering component, sheet, formula, and use-trigger cases.
+ ///
+ /// The workbook fixture.
+ public static ExcelTemplateWorkbook CreateStandardWorkbook() =>
+ new(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Header",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "請求書", null, new ExcelTemplateStyle(3)),
+ new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@items, var:item}}", null, null),
+ new ExcelTemplateCell("B2", 2, 2, null, "SUM(C1:C3)", new ExcelTemplateStyle(7)),
+ new ExcelTemplateCell("C3", 3, 3, "ignored", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "__component_ItemRow",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "@item.Name", null, null),
+ ]),
+ new ExcelTemplateSheet(
+ "Invoice",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Header}}", null, null),
+ new ExcelTemplateCell("B3", 3, 2, null, "SUM(B4:B8)", null),
+ ]),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$B$2",
+ });
+
+ ///
+ /// Creates a workbook fixture containing unresolved component and validation issues.
+ ///
+ /// The workbook fixture.
+ public static ExcelTemplateWorkbook CreateWorkbookWithIssues() =>
+ new(
+ sheets:
+ [
+ new ExcelTemplateSheet("__component_Empty"),
+ new ExcelTemplateSheet(
+ "Summary",
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Missing", null, null),
+ ],
+ hasConditionalFormatting: true),
+ ]);
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs
new file mode 100644
index 0000000..1bda673
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs
@@ -0,0 +1,148 @@
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+using ExcelReportLib.Renderer;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides integration tests for .
+///
+public sealed class ExcelTemplateReportGeneratorTests
+{
+ ///
+ /// Verifies that the ExcelTemplate facade converts and renders a workbook through the existing report pipeline.
+ ///
+ [Fact]
+ public void GenerateFromExcelTemplate_ValidWorkbook_ProducesXlsx()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateReportWorkbookFile();
+
+ try
+ {
+ var generator = new ExcelTemplateReportGenerator();
+
+ var result = generator.GenerateFromExcelTemplate(
+ xlsxPath,
+ new { Title = "Sales" },
+ CreateOptions());
+
+ Assert.NotNull(result.Output);
+ Assert.True(result.Succeeded);
+ Assert.DoesNotContain(result.Issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal);
+
+ using var document = OpenWorkbook(result);
+ Assert.Equal("Sales", ReadCellValue(document, GetCell(document, "Summary", "A1")));
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that fatal conversion failures abort before the DSL report pipeline runs.
+ ///
+ [Fact]
+ public void GenerateFromExcelTemplate_CorruptWorkbook_ReturnsFatalLoadIssue()
+ {
+ var xlsxPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx");
+ File.WriteAllText(xlsxPath, "not-an-xlsx");
+
+ try
+ {
+ var generator = new ExcelTemplateReportGenerator();
+
+ var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions());
+
+ Assert.Null(result.Output);
+ Assert.True(result.AbortedByFatal);
+ var issue = Assert.Single(result.Issues);
+ Assert.Equal(IssueSeverity.Fatal, issue.Severity);
+ Assert.Equal(IssueKind.LoadFile, issue.Kind);
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ ///
+ /// Verifies that non-fatal conversion issues are preserved on the final report result.
+ ///
+ [Fact]
+ public void GenerateFromExcelTemplate_WithNonFatalConversionIssue_ReturnsOutputAndIssues()
+ {
+ var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateReportWorkbookWithConversionIssueFile();
+
+ try
+ {
+ var generator = new ExcelTemplateReportGenerator();
+
+ var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions());
+
+ Assert.NotNull(result.Output);
+ Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange);
+
+ using var document = OpenWorkbook(result);
+ Assert.Equal("Ready", ReadCellValue(document, GetCell(document, "Summary", "A1")));
+ }
+ finally
+ {
+ File.Delete(xlsxPath);
+ }
+ }
+
+ private static ExcelTemplateGenerateOptions CreateOptions() =>
+ new()
+ {
+ ReportGeneratorOptions = new ReportGeneratorOptions
+ {
+ EnableSchemaValidation = false,
+ RenderOptions = new RenderOptions
+ {
+ TemplateName = "Task11",
+ DataSource = "Tests",
+ GeneratedAt = new DateTimeOffset(2026, 4, 14, 0, 0, 0, TimeSpan.Zero),
+ },
+ },
+ };
+
+ private static SpreadsheetDocument OpenWorkbook(ReportGeneratorResult result)
+ {
+ var output = Assert.IsType(result.Output);
+ output.Position = 0;
+ return SpreadsheetDocument.Open(output, false);
+ }
+
+ private static WorksheetPart GetWorksheetPart(SpreadsheetDocument document, string sheetName) =>
+ (WorksheetPart)document.WorkbookPart!.GetPartById(
+ document.WorkbookPart.Workbook.Sheets!.Elements()
+ .Single(sheet => sheet.Name!.Value == sheetName)
+ .Id!);
+
+ private static Cell GetCell(SpreadsheetDocument document, string sheetName, string reference) =>
+ GetWorksheetPart(document, sheetName)
+ .Worksheet
+ .Descendants()
+ .Single(cell => cell.CellReference!.Value == reference);
+
+ private static string ReadCellValue(SpreadsheetDocument document, Cell cell)
+ {
+ if (cell.DataType?.Value == CellValues.InlineString)
+ {
+ return cell.InlineString!.InnerText;
+ }
+
+ if (cell.DataType?.Value == CellValues.SharedString)
+ {
+ return document.WorkbookPart!.SharedStringTablePart!.SharedStringTable
+ .Elements()
+ .ElementAt(int.Parse(cell.CellValue!.Text, System.Globalization.CultureInfo.InvariantCulture))
+ .InnerText;
+ }
+
+ return cell.CellValue?.Text ?? string.Empty;
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs
new file mode 100644
index 0000000..10bc83b
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs
@@ -0,0 +1,47 @@
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides snapshot tests for ExcelTemplate conversion outputs.
+///
+public sealed class ExcelTemplateSnapshotTests
+{
+ private const string XmlSnapshotFile = "Issue58_StandardTemplate_Debug.xml";
+ private const string DslSnapshotFile = "Issue58_StandardTemplate_Dsl.xml";
+
+ ///
+ /// Verifies that serializer output matches the checked-in debug XML snapshot.
+ ///
+ [Fact]
+ public void Serialize_StandardWorkbook_MatchesXmlSnapshot()
+ {
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook());
+ var serializer = new XmlTemplateSerializer();
+
+ var actual = NormalizeLineEndings(serializer.Serialize(contract).ToString());
+ var expected = NormalizeLineEndings(DslTestFixtures.ReadText(XmlSnapshotFile));
+
+ Assert.Equal(expected, actual);
+ }
+
+ ///
+ /// Verifies that DSL emitter output matches the checked-in DSL snapshot.
+ ///
+ [Fact]
+ public void Emit_StandardWorkbook_MatchesDslSnapshot()
+ {
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook());
+ var emitter = new DslEmitter();
+
+ var actual = NormalizeLineEndings(emitter.Emit(contract));
+ var expected = NormalizeLineEndings(DslTestFixtures.ReadText(DslSnapshotFile));
+
+ Assert.Equal(expected, actual);
+ }
+
+ private static string NormalizeLineEndings(string value) =>
+ value.Replace("\r\n", "\n", StringComparison.Ordinal).Trim();
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs
new file mode 100644
index 0000000..a3e781c
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs
@@ -0,0 +1,423 @@
+using System.Globalization;
+using DocumentFormat.OpenXml;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Creates temporary xlsx fixtures for ExcelTemplate conversion tests.
+///
+internal static class ExcelTemplateTestWorkbookFactory
+{
+ ///
+ /// Creates a valid workbook fixture.
+ ///
+ /// The temporary workbook path.
+ public static string CreateStandardWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var componentSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "請求書"),
+ CreateInlineStringCell("A2", "{{use:ItemRow, from:@items, var:item}}"),
+ CreateFormulaCell("B2", "SUM(C1:C3)"),
+ ]);
+ var itemRowSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 2U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "@item.Name"),
+ ]);
+ var invoiceSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 3U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "{{use:Header}}"),
+ CreateFormulaCell("B3", "SUM(B4:B8)"),
+ ]);
+
+ sheets.Append(
+ CreateSheet(componentSheetPart, workbookPart, "__component_Header", 1U),
+ CreateSheet(itemRowSheetPart, workbookPart, "__component_ItemRow", 2U),
+ CreateSheet(invoiceSheetPart, workbookPart, "Invoice", 3U));
+
+ workbookPart.Workbook.DefinedNames = new DefinedNames(
+ new DefinedName
+ {
+ Name = "__component_range_Header",
+ Text = "'__component_Header'!$A$1:$B$2",
+ });
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates an invalid workbook fixture that still allows conversion output.
+ ///
+ /// The temporary workbook path.
+ public static string CreateIssueWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var emptyComponentSheetPart = CreateWorksheetPart(workbookPart, sheetId: 1U, cells: []);
+ var summarySheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 2U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "{{use:Missing"),
+ ],
+ hasConditionalFormatting: true);
+
+ sheets.Append(
+ CreateSheet(emptyComponentSheetPart, workbookPart, "__component_Empty", 1U),
+ CreateSheet(summarySheetPart, workbookPart, "Summary", 2U));
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a workbook fixture that emits a DSL cell with both value and formula attributes.
+ ///
+ /// The temporary workbook path.
+ public static string CreateFormulaValueConflictWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var worksheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateFormulaInlineStringCell("A1", "TemplateValue", "SUM(B1:B2)"),
+ ]);
+
+ sheets.Append(CreateSheet(worksheetPart, workbookPart, "Invoice", 1U));
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a workbook fixture with a well-formed use trigger that references an undefined component.
+ ///
+ /// The temporary workbook path.
+ public static string CreateUndefinedComponentWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var worksheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "{{use:Missing}}"),
+ ]);
+
+ sheets.Append(CreateSheet(worksheetPart, workbookPart, "Invoice", 1U));
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a workbook fixture for end-to-end report generation through the ExcelTemplate facade.
+ ///
+ /// The temporary workbook path.
+ public static string CreateReportWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var summarySheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "@(root.Title)"),
+ ]);
+
+ sheets.Append(CreateSheet(summarySheetPart, workbookPart, "Summary", 1U));
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a report workbook fixture that carries a non-fatal conversion issue.
+ ///
+ /// The temporary workbook path.
+ public static string CreateReportWorkbookWithConversionIssueFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var emptyComponentSheetPart = CreateWorksheetPart(workbookPart, sheetId: 1U, cells: []);
+ var summarySheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 2U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "Ready"),
+ ]);
+
+ sheets.Append(
+ CreateSheet(emptyComponentSheetPart, workbookPart, "__component_Empty", 1U),
+ CreateSheet(summarySheetPart, workbookPart, "Summary", 2U));
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a nested workbook fixture that exercises GroupBlock, ItemRow, styleOverflow, and formula preservation.
+ ///
+ /// The temporary workbook path.
+ public static string CreateNestedReportWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var headerSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "Invoice"),
+ CreateFormulaCell("B1", "SUM(B4:B8)"),
+ ]);
+ var itemRowSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 2U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "@item.Name"),
+ CreateInlineStringCell("B1", "@item.Qty"),
+ CreateInlineStringCell("C1", "@item.Price"),
+ ]);
+ var groupBlockSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 3U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "@group.Name"),
+ CreateInlineStringCell("A2", "{{use:ItemRow, from:@group.Items, var:item, styleOverflow:edge}}"),
+ ]);
+ var invoiceSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 4U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "{{use:Header, styleOverflow:edge}}"),
+ CreateInlineStringCell("A3", "{{use:GroupBlock, from:@groups, var:group, styleOverflow:edge}}"),
+ ]);
+
+ sheets.Append(
+ CreateSheet(headerSheetPart, workbookPart, "__component_Header", 1U),
+ CreateSheet(itemRowSheetPart, workbookPart, "__component_ItemRow", 2U),
+ CreateSheet(groupBlockSheetPart, workbookPart, "__component_GroupBlock", 3U),
+ CreateSheet(invoiceSheetPart, workbookPart, "Invoice", 4U));
+
+ workbookPart.Workbook.DefinedNames = new DefinedNames(
+ new DefinedName
+ {
+ Name = "__component_range_Header",
+ Text = "'__component_Header'!$A$1:$B$1",
+ },
+ new DefinedName
+ {
+ Name = "__component_range_ItemRow",
+ Text = "'__component_ItemRow'!$A$1:$C$1",
+ },
+ new DefinedName
+ {
+ Name = "__component_range_GroupBlock",
+ Text = "'__component_GroupBlock'!$A$1:$C$2",
+ });
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ ///
+ /// Creates a workbook fixture that emits merged-boundary and unsupported-feature issues.
+ ///
+ /// The temporary workbook path.
+ public static string CreateValidationIssueWorkbookFile()
+ {
+ var path = CreateEmptyWorkbookFile();
+
+ using var document = SpreadsheetDocument.Open(path, true);
+ var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created.");
+ var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets());
+
+ var badComponentSheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 1U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "Broken"),
+ ],
+ mergedRanges:
+ [
+ "A1:C1",
+ ]);
+ var summarySheetPart = CreateWorksheetPart(
+ workbookPart,
+ sheetId: 2U,
+ cells:
+ [
+ CreateInlineStringCell("A1", "Ready"),
+ ],
+ hasConditionalFormatting: true);
+
+ sheets.Append(
+ CreateSheet(badComponentSheetPart, workbookPart, "__component_Bad", 1U),
+ CreateSheet(summarySheetPart, workbookPart, "Summary", 2U));
+
+ workbookPart.Workbook.DefinedNames = new DefinedNames(
+ new DefinedName
+ {
+ Name = "__component_range_Bad",
+ Text = "'__component_Bad'!$A$1:$B$1",
+ });
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ private static string CreateEmptyWorkbookFile()
+ {
+ var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx");
+
+ using var document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook);
+ var workbookPart = document.AddWorkbookPart();
+ workbookPart.Workbook = new Workbook();
+ workbookPart.Workbook.AppendChild(new Sheets());
+ workbookPart.Workbook.Save();
+
+ return path;
+ }
+
+ private static WorksheetPart CreateWorksheetPart(
+ WorkbookPart workbookPart,
+ uint sheetId,
+ IReadOnlyList cells,
+ bool hasConditionalFormatting = false,
+ IReadOnlyList? mergedRanges = null)
+ {
+ var worksheetPart = workbookPart.AddNewPart($"rId{sheetId}");
+ var worksheet = new Worksheet();
+ var sheetData = worksheet.AppendChild(new SheetData());
+ var rows = cells
+ .GroupBy(cell => GetRowIndex(cell.CellReference?.Value ?? string.Empty))
+ .OrderBy(group => group.Key);
+
+ foreach (var rowGroup in rows)
+ {
+ var row = new Row { RowIndex = rowGroup.Key };
+ foreach (var cell in rowGroup.OrderBy(cell => cell.CellReference!.Value, StringComparer.Ordinal))
+ {
+ row.Append(cell);
+ }
+
+ sheetData.Append(row);
+ }
+
+ if (hasConditionalFormatting)
+ {
+ worksheet.Append(
+ new ConditionalFormatting
+ {
+ SequenceOfReferences = new ListValue { InnerText = "A1" },
+ });
+ }
+
+ if (mergedRanges is { Count: > 0 })
+ {
+ var mergeCells = new MergeCells();
+ foreach (var mergedRange in mergedRanges)
+ {
+ mergeCells.Append(new MergeCell { Reference = mergedRange });
+ }
+
+ worksheet.Append(mergeCells);
+ }
+
+ worksheetPart.Worksheet = worksheet;
+ worksheetPart.Worksheet.Save();
+ return worksheetPart;
+ }
+
+ private static Sheet CreateSheet(WorksheetPart worksheetPart, WorkbookPart workbookPart, string name, uint sheetId) =>
+ new()
+ {
+ Id = workbookPart.GetIdOfPart(worksheetPart),
+ Name = name,
+ SheetId = sheetId,
+ };
+
+ private static Cell CreateInlineStringCell(string reference, string value) =>
+ new()
+ {
+ CellReference = reference,
+ DataType = CellValues.InlineString,
+ InlineString = new InlineString(new Text(value)),
+ };
+
+ private static Cell CreateFormulaCell(string reference, string formula) =>
+ new()
+ {
+ CellReference = reference,
+ CellFormula = new CellFormula(formula),
+ };
+
+ private static Cell CreateFormulaInlineStringCell(string reference, string value, string formula) =>
+ new()
+ {
+ CellReference = reference,
+ DataType = CellValues.InlineString,
+ InlineString = new InlineString(new Text(value)),
+ CellFormula = new CellFormula(formula),
+ };
+
+ private static uint GetRowIndex(string cellReference)
+ {
+ var digits = new string(cellReference.Where(char.IsDigit).ToArray());
+ return uint.Parse(digits, CultureInfo.InvariantCulture);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs
new file mode 100644
index 0000000..d2ca3d8
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs
@@ -0,0 +1,138 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class ExcelTemplateUseTriggerParserTests
+{
+ ///
+ /// Verifies that non-trigger text is ignored without issues.
+ ///
+ [Fact]
+ public void Parse_PlainText_ReturnsNotTrigger()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("請求書");
+
+ Assert.False(result.IsTrigger);
+ Assert.Null(result.Trigger);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that simple use trigger parses component only.
+ ///
+ [Fact]
+ public void Parse_SimpleUse_ReturnsComponentTrigger()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("{{use:Header}}");
+
+ Assert.True(result.IsTrigger);
+ var trigger = Assert.IsType(result.Trigger);
+ Assert.Equal("Header", trigger.ComponentName);
+ Assert.Null(trigger.FromExpression);
+ Assert.Null(trigger.VariableName);
+ Assert.Null(trigger.RepeatDirection);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that repeat use trigger parses from and var and normalizes direction down.
+ ///
+ [Fact]
+ public void Parse_RepeatUse_ReturnsRepeatTrigger()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("{{use:ItemRow, from:@items, var:item}}");
+
+ Assert.True(result.IsTrigger);
+ var trigger = Assert.IsType(result.Trigger);
+ Assert.Equal("ItemRow", trigger.ComponentName);
+ Assert.Equal("@items", trigger.FromExpression);
+ Assert.Equal("item", trigger.VariableName);
+ Assert.Equal("down", trigger.RepeatDirection);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that styleOverflow token is parsed for both use and repeat-use triggers.
+ ///
+ [Fact]
+ public void Parse_UseWithStyleOverflow_ReturnsOverflowMode()
+ {
+ var parser = new UseTriggerParser();
+
+ var simpleResult = parser.Parse("{{use:Header, styleOverflow:edge}}");
+ var repeatResult = parser.Parse("{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}");
+
+ Assert.True(simpleResult.IsTrigger);
+ Assert.Equal("edge", Assert.IsType(simpleResult.Trigger).StyleOverflow);
+
+ Assert.True(repeatResult.IsTrigger);
+ Assert.Equal("edge", Assert.IsType(repeatResult.Trigger).StyleOverflow);
+ }
+
+ ///
+ /// Verifies that commas inside from expression do not break trigger tokenization.
+ ///
+ [Fact]
+ public void Parse_RepeatUse_WithCommaInFromExpression_ReturnsRepeatTrigger()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("{{use:ItemRow, from:@(root.Items.Select((x, i) => new { x, i })), var:item}}");
+
+ Assert.True(result.IsTrigger);
+ var trigger = Assert.IsType(result.Trigger);
+ Assert.Equal("ItemRow", trigger.ComponentName);
+ Assert.Equal("@(root.Items.Select((x, i) => new { x, i }))", trigger.FromExpression);
+ Assert.Equal("item", trigger.VariableName);
+ Assert.Equal("down", trigger.RepeatDirection);
+ Assert.Empty(result.Issues);
+ }
+
+ ///
+ /// Verifies that from without var returns error.
+ ///
+ [Fact]
+ public void Parse_FromWithoutVar_ReturnsError()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("{{use:ItemRow, from:@items}}");
+
+ Assert.True(result.IsTrigger);
+ Assert.Null(result.Trigger);
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.InvalidAttributeValue
+ && issue.Message.Contains("var", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Verifies that var without from returns error.
+ ///
+ [Fact]
+ public void Parse_VarWithoutFrom_ReturnsError()
+ {
+ var parser = new UseTriggerParser();
+
+ var result = parser.Parse("{{use:ItemRow, var:item}}");
+
+ Assert.True(result.IsTrigger);
+ Assert.Null(result.Trigger);
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.InvalidAttributeValue
+ && issue.Message.Contains("from", StringComparison.Ordinal));
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs
new file mode 100644
index 0000000..31fc62a
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs
@@ -0,0 +1,124 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class ExcelTemplateValidatorTests
+{
+ ///
+ /// Verifies that merged range crossing component boundary returns error.
+ ///
+ [Fact]
+ public void Validate_MergedRangeCrossingComponentBoundary_ReturnsError()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "__component_Header",
+ cells:
+ [
+ new ExcelTemplateCell("A1", 1, 1, "Title", null, null),
+ ],
+ mergedRanges: ["A1:C1"]),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1",
+ });
+ var resolver = new ExcelTemplateComponentRangeResolver();
+ var ranges = resolver.Resolve(workbook);
+ var validator = new ExcelTemplateValidator();
+
+ var result = validator.Validate(workbook, ranges.Ranges);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error &&
+ issue.Kind == IssueKind.MergedCellBoundaryViolation &&
+ issue.Message.Contains("__component_Header", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Verifies that malformed use trigger returns cell-scoped error.
+ ///
+ [Fact]
+ public void Validate_InvalidUseTrigger_ReturnsError()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "Summary",
+ cells:
+ [
+ new ExcelTemplateCell("B3", 3, 2, "{{use:ItemRow, from:@items}}", null, null),
+ ]),
+ ]);
+ var validator = new ExcelTemplateValidator();
+
+ var result = validator.Validate(workbook, []);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error &&
+ issue.Kind == IssueKind.InvalidAttributeValue &&
+ issue.Message.Contains("Summary", StringComparison.Ordinal) &&
+ issue.Message.Contains("B3", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Verifies that conditional formatting is reported as unsupported for the initial release.
+ ///
+ [Fact]
+ public void Validate_SheetWithConditionalFormatting_ReturnsUnsupportedFeature()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "Summary",
+ hasConditionalFormatting: true),
+ ]);
+ var validator = new ExcelTemplateValidator();
+
+ var result = validator.Validate(workbook, []);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error &&
+ issue.Kind == IssueKind.UnsupportedExcelTemplateFeature &&
+ issue.Message.Contains("conditional formatting", StringComparison.OrdinalIgnoreCase));
+ }
+
+ ///
+ /// Verifies that use trigger referencing unknown component returns undefined component error.
+ ///
+ [Fact]
+ public void Validate_UseTriggerReferencingUnknownComponent_ReturnsError()
+ {
+ var workbook = new ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplateSheet(
+ "Summary",
+ cells:
+ [
+ new ExcelTemplateCell("A1", 1, 1, "{{use:Missing}}", null, null),
+ ]),
+ ]);
+ var validator = new ExcelTemplateValidator();
+
+ var result = validator.Validate(workbook, []);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error &&
+ issue.Kind == IssueKind.UndefinedComponent &&
+ issue.Message.Contains("Missing", StringComparison.Ordinal));
+ }
+}
diff --git a/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs b/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs
index ace5b39..a37ddd7 100644
--- a/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs
+++ b/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs
@@ -979,6 +979,30 @@ public void Expand_FormulaRefAndFormulaPlaceholder_PreservedForStateBuild()
Assert.Equal("=SUM(#{Detail.Value:Detail.ValueEnd})", totalsCell.Formula);
}
+ ///
+ /// Verifies that explicit cell formula is preserved for state build.
+ ///
+ [Fact]
+ public void Expand_CellFormula_PreservedForStateBuild()
+ {
+ var plan = Expand(
+ """
+
+
+ |
+
+
+ """);
+
+ var cell = Assert.Single(Assert.Single(plan.Sheets).Cells);
+
+ Assert.Equal(2, cell.Row);
+ Assert.Equal(3, cell.Col);
+ Assert.Null(cell.Value);
+ Assert.Equal("=SUM(B2:B10)", cell.Formula);
+ Assert.Empty(plan.Issues);
+ }
+
///
/// Verifies that expression value returning '=...' is treated as Excel formula.
///
@@ -1071,6 +1095,156 @@ public void Expand_GridAutoSize_AccountsForChildOffsetsInRepeatDirections()
Assert.Equal(15, cellsByValue["R2"].Col);
}
+ ///
+ /// Verifies that use style overflow none does not extend seed styles into overflow area.
+ ///
+ [Fact]
+ public void Expand_UseStyleOverflowNone_DoesNotCopySeedStyles()
+ {
+ var plan = Expand(
+ """
+
+
+
+ |
+ |
+ |
+ |
+
+
+
+
+
+
+ """);
+
+ var sheet = Assert.Single(plan.Sheets);
+ var overflowCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 4);
+
+ Assert.Null(overflowCell.StylePlan.FillColor);
+ Assert.DoesNotContain(
+ plan.Issues,
+ issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal);
+ }
+
+ ///
+ /// Verifies that use style overflow edge copies seed styles into overflow area.
+ ///
+ [Fact]
+ public void Expand_UseStyleOverflowEdge_CopiesSeedStyles()
+ {
+ var plan = Expand(
+ """
+
+
+
+ |
+ |
+ |
+ |
+
+
+
+
+
+
+ """);
+
+ var sheet = Assert.Single(plan.Sheets);
+ var overflowCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 4);
+ var anchorCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 3);
+
+ Assert.Equal("#FFDD99", anchorCell.StylePlan.FillColor);
+ Assert.Equal("#FFDD99", overflowCell.StylePlan.FillColor);
+ Assert.Contains(
+ plan.Issues,
+ issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning);
+ }
+
+ ///
+ /// Verifies that use style overflow edge copies seed styles downward into overflow rows.
+ ///
+ [Fact]
+ public void Expand_UseStyleOverflowEdge_CopiesSeedStylesDownward()
+ {
+ var plan = Expand(
+ """
+
+
+
+ |
+ |
+ |
+ |
+
+
+
+
+
+
+ """);
+
+ var sheet = Assert.Single(plan.Sheets);
+ var anchorCell = sheet.Cells.Single(cell => cell.Row == 3 && cell.Col == 1);
+ var overflowCell = sheet.Cells.Single(cell => cell.Row == 4 && cell.Col == 1);
+
+ Assert.Equal("#99DDFF", anchorCell.StylePlan.FillColor);
+ Assert.Equal("#99DDFF", overflowCell.StylePlan.FillColor);
+ Assert.Contains(
+ plan.Issues,
+ issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning);
+ }
+
+ ///
+ /// Verifies that use style overflow edge copies corner seed styles into overflow corner cells.
+ ///
+ [Fact]
+ public void Expand_UseStyleOverflowEdge_CopiesSeedStylesIntoOverflowCorner()
+ {
+ var plan = Expand(
+ """
+
+
+
+ |
+ |
+ |
+ |
+
+
+
+
+
+
+ """);
+
+ var sheet = Assert.Single(plan.Sheets);
+ var anchorCornerCell = sheet.Cells.Single(cell => cell.Row == 3 && cell.Col == 4);
+ var overflowCornerCell = sheet.Cells.Single(cell => cell.Row == 4 && cell.Col == 5);
+
+ Assert.Equal("#DDBBFF", anchorCornerCell.StylePlan.FillColor);
+ Assert.Equal("#DDBBFF", overflowCornerCell.StylePlan.FillColor);
+ Assert.Contains(
+ plan.Issues,
+ issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning);
+ }
+
///
/// Verifies that expand sheet from expression expands multiple sheets.
///
diff --git a/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs b/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs
index 1e595e2..aded668 100644
--- a/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs
+++ b/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs
@@ -90,6 +90,24 @@ public void Parse_Cell_FormulaRefScope_ReadsAttribute()
Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal);
}
+ ///
+ /// Verifies that parse cell formula attribute reads formula raw.
+ ///
+ [Fact]
+ public void Parse_Cell_Formula_ReadsAttribute()
+ {
+ var issues = new List();
+ var cellElement = XElement.Parse(
+ """
+ |
+ """);
+
+ var cell = Assert.IsType(LayoutNodeAst.LayoutNodeAstFactory(cellElement, issues));
+
+ Assert.Equal("SUM(B2:B10)", cell.FormulaRaw);
+ Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal);
+ }
+
///
/// Verifies that parse cell invalid formula ref scope falls back to global with warning.
///
@@ -191,6 +209,24 @@ public void Parse_Use_HasAreaAttribute()
Assert.Equal("Title", use.ComponentName);
}
+ ///
+ /// Verifies that parse use reads style overflow attribute.
+ ///
+ [Fact]
+ public void Parse_Use_StyleOverflow_ReadsAttribute()
+ {
+ var issues = new List();
+ var useElement = XElement.Parse(
+ """
+
+ """);
+
+ var use = Assert.IsType(LayoutNodeAst.LayoutNodeAstFactory(useElement, issues));
+
+ Assert.Equal("edge", use.StyleOverflow);
+ Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal);
+ }
+
///
/// Verifies that parse grid child nodes.
///
@@ -231,4 +267,3 @@ public void Parse_Grid_HasAreaAttribute()
Assert.Equal("GridArea", grid.AreaName);
}
}
-
diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd b/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd
index a16f95e..10bd2b6 100644
--- a/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd
+++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd
@@ -295,6 +295,7 @@
+
@@ -313,6 +314,7 @@
+
| | | |
@@ -330,6 +332,13 @@
+
+
+
+
+
+
+
diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml
new file mode 100644
index 0000000..02f0dac
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml
@@ -0,0 +1,22 @@
+
+
+
+
+ |
+
+
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+ |
+
+
diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml
new file mode 100644
index 0000000..d7d7cdf
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+ |
+
+
+
+ |
+
+
+
+
+
+ |
+
+
+
+
+ |
+
+
diff --git a/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs b/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs
index 816c7e8..c77d9c4 100644
--- a/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs
+++ b/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs
@@ -292,6 +292,56 @@ public void ValidateDsl_SheetVarElementWithoutFrom_ReturnsError()
&& issue.Message.Contains("from"));
}
+ ///
+ /// Verifies that validate DSL formula and value conflict returns error.
+ ///
+ [Fact]
+ public void ValidateDsl_CellFormulaAndValueConflict_ReturnsError()
+ {
+ var result = ParseDsl(
+ """
+
+
+ |
+
+
+ """);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.InvalidAttributeValue
+ && issue.Message.Contains("formula", StringComparison.Ordinal)
+ && issue.Message.Contains("value", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Verifies that validate DSL invalid style overflow returns error.
+ ///
+ [Fact]
+ public void ValidateDsl_InvalidStyleOverflow_ReturnsError()
+ {
+ var result = ParseDsl(
+ """
+
+
+
+ |
+
+
+
+
+
+
+ """);
+
+ Assert.Contains(
+ result.Issues,
+ issue => issue.Severity == IssueSeverity.Error
+ && issue.Kind == IssueKind.InvalidAttributeValue
+ && issue.Message.Contains("styleOverflow", StringComparison.Ordinal));
+ }
+
private static DslParseResult ParseDsl(string xml) =>
DslParser.ParseFromText(
xml,
@@ -301,4 +351,3 @@ private static DslParseResult ParseDsl(string xml) =>
});
}
-
diff --git a/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs b/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs
new file mode 100644
index 0000000..bca2e61
--- /dev/null
+++ b/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs
@@ -0,0 +1,175 @@
+using System.Xml.Linq;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate;
+
+namespace ExcelReportLib.Tests;
+
+///
+/// Provides tests for .
+///
+public sealed class XmlTemplateSerializerTests
+{
+ ///
+ /// Verifies that serializer writes DSL-compatible workbook, component, sheet, cell, use, and repeat structures.
+ ///
+ [Fact]
+ public void Serialize_WritesDslCompatibleWorkbookComponentsSheetsAndItems()
+ {
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook());
+ var serializer = new XmlTemplateSerializer();
+
+ var document = serializer.Serialize(contract);
+ var root = Assert.IsType(document.Root);
+
+ Assert.Equal("workbook", root.Name.LocalName);
+ Assert.Equal("urn:excelreport:v2", root.Name.NamespaceName);
+
+ var header = root.Elements(root.Name.Namespace + "component").Single(element => (string?)element.Attribute("name") == "Header");
+ var grid = Assert.Single(header.Elements(root.Name.Namespace + "grid"));
+ Assert.Equal("2", (string?)grid.Attribute("rows"));
+ Assert.Equal("2", (string?)grid.Attribute("cols"));
+
+ var headerItems = grid.Elements().ToArray();
+ Assert.Equal("cell", headerItems[0].Name.LocalName);
+ Assert.Equal("1", (string?)headerItems[0].Attribute("r"));
+ Assert.Equal("1", (string?)headerItems[0].Attribute("c"));
+ Assert.Equal("請求書", (string?)headerItems[0].Attribute("value"));
+ Assert.Equal("repeat", headerItems[1].Name.LocalName);
+ Assert.Equal("2", (string?)headerItems[1].Attribute("r"));
+ Assert.Equal("1", (string?)headerItems[1].Attribute("c"));
+ Assert.Equal("@(root.Items)", (string?)headerItems[1].Attribute("from"));
+ Assert.Equal("item", (string?)headerItems[1].Attribute("var"));
+ Assert.Equal("down", (string?)headerItems[1].Attribute("direction"));
+ Assert.Equal("use", headerItems[1].Elements().Single().Name.LocalName);
+ Assert.Equal("ItemRow", (string?)headerItems[1].Elements().Single().Attribute("component"));
+ Assert.Equal("cell", headerItems[2].Name.LocalName);
+ Assert.Equal("SUM(C1:C3)", (string?)headerItems[2].Attribute("formula"));
+
+ var invoice = Assert.Single(root.Elements(root.Name.Namespace + "sheet"));
+ Assert.Equal("Invoice", (string?)invoice.Attribute("name"));
+ Assert.Equal("use", invoice.Elements().First().Name.LocalName);
+ Assert.Equal("Header", (string?)invoice.Elements().First().Attribute("component"));
+ var itemRow = root.Elements(root.Name.Namespace + "component").Single(element => (string?)element.Attribute("name") == "ItemRow");
+ var itemNameCell = Assert.Single(itemRow.Descendants(root.Name.Namespace + "cell"));
+ Assert.Equal("@(item.Name)", (string?)itemNameCell.Attribute("value"));
+
+ var parseResult = DslParser.ParseFromText(
+ document.ToString(),
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+
+ ///
+ /// Verifies that serializer keeps DSL compatibility while preserving unresolved context and issues in comments.
+ ///
+ [Fact]
+ public void Serialize_UnresolvedComponentAndIssues_ArePreservedInComments()
+ {
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateWorkbookWithIssues());
+ var serializer = new XmlTemplateSerializer();
+
+ var document = serializer.Serialize(contract);
+ var root = Assert.IsType(document.Root);
+
+ Assert.Empty(root.Elements(root.Name.Namespace + "component"));
+ var comments = root.Nodes().OfType().Select(comment => comment.Value).ToArray();
+ Assert.Contains(comments, comment => comment.Contains("unresolved-component", StringComparison.Ordinal));
+ Assert.Contains(comments, comment => comment.Contains("EmptyComponentRange", StringComparison.Ordinal));
+ Assert.Contains(comments, comment => comment.Contains("UnsupportedExcelTemplateFeature", StringComparison.Ordinal));
+
+ var summary = Assert.Single(root.Elements(root.Name.Namespace + "sheet"));
+ var malformedCell = Assert.Single(summary.Elements(root.Name.Namespace + "cell"));
+ Assert.Equal("{{use:Missing", (string?)malformedCell.Attribute("value"));
+
+ var parseResult = DslParser.ParseFromText(
+ document.ToString(),
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+
+ ///
+ /// Verifies that style-only cells are serialized as empty DSL cells without breaking schema compatibility.
+ ///
+ [Fact]
+ public void Serialize_StyleOnlyCell_RemainsDslCompatible()
+ {
+ var workbook = new ExcelTemplate.Model.ExcelTemplateWorkbook(
+ sheets:
+ [
+ new ExcelTemplate.Model.ExcelTemplateSheet(
+ "__component_Header",
+ [
+ new ExcelTemplate.Model.ExcelTemplateCell("A1", 1, 1, "Title", null, null),
+ new ExcelTemplate.Model.ExcelTemplateCell("B1", 1, 2, null, null, new ExcelTemplate.Model.ExcelTemplateStyle(11)),
+ ]),
+ new ExcelTemplate.Model.ExcelTemplateSheet("Invoice"),
+ ],
+ definedNames: new Dictionary(StringComparer.Ordinal)
+ {
+ ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1",
+ });
+
+ var builder = new ExcelTemplateOutputContractBuilder();
+ var contract = builder.Build(workbook);
+ var serializer = new XmlTemplateSerializer();
+
+ var document = serializer.Serialize(contract);
+ var root = Assert.IsType(document.Root);
+ var header = Assert.Single(root.Elements(root.Name.Namespace + "component"));
+ var cells = header.Descendants(root.Name.Namespace + "cell").ToArray();
+ Assert.Equal(2, cells.Length);
+ Assert.Null(cells[1].Attribute("value"));
+ Assert.Null(cells[1].Attribute("formula"));
+
+ var parseResult = DslParser.ParseFromText(
+ document.ToString(),
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+
+ ///
+ /// Verifies that explicit styleOverflow values are emitted on use and repeat-use nodes.
+ ///
+ [Fact]
+ public void Serialize_ExplicitStyleOverflow_EmitsDslAttributes()
+ {
+ var contract = new ExcelTemplate.Model.ExcelTemplateOutputContract(
+ components:
+ [
+ new ExcelTemplate.Model.ExcelTemplateOutputComponent(
+ "Header",
+ "__component_Header",
+ "A1:A2",
+ isRangeResolved: true,
+ items:
+ [
+ new ExcelTemplate.Model.ExcelTemplateOutputUse("A1", 1, 1, null, "ItemRow", "edge"),
+ new ExcelTemplate.Model.ExcelTemplateOutputRepeatUse("A2", 2, 1, null, "ItemRow", "@items", "item", "down", "edge"),
+ ]),
+ ],
+ sheets:
+ [
+ new ExcelTemplate.Model.ExcelTemplateOutputSheet("Invoice"),
+ ]);
+ var serializer = new XmlTemplateSerializer();
+
+ var document = serializer.Serialize(contract);
+ var root = Assert.IsType(document.Root);
+ var use = root.Descendants(root.Name.Namespace + "use").First();
+ var repeatUse = root.Descendants(root.Name.Namespace + "repeat").Single().Elements(root.Name.Namespace + "use").Single();
+
+ Assert.Equal("edge", (string?)use.Attribute("styleOverflow"));
+ Assert.Equal("edge", (string?)repeatUse.Attribute("styleOverflow"));
+
+ var parseResult = DslParser.ParseFromText(
+ document.ToString(),
+ new DslParserOptions { EnableSchemaValidation = true });
+ Assert.NotNull(parseResult.Root);
+ Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs
index 1147bc9..042ad96 100644
--- a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs
+++ b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs
@@ -19,6 +19,10 @@ public sealed class CellAst : LayoutNodeAst, IAst
///
public string? ValueRaw { get; init; }
///
+ /// Gets or sets the formula raw.
+ ///
+ public string? FormulaRaw { get; init; }
+ ///
/// Gets or sets the style ref shortcut.
///
public string? StyleRefShortcut { get; init; }
@@ -39,6 +43,7 @@ public sealed class CellAst : LayoutNodeAst, IAst
public CellAst(XElement elem, List issues)
{
var valueAttr = elem.Attribute("value");
+ var formulaAttr = elem.Attribute("formula");
var styleRefAttr = elem.Attribute("styleRef");
var formulaRefAttr = elem.Attribute("formulaRef");
var formulaRefScopeAttr = elem.Attribute("formulaRefScope");
@@ -49,10 +54,10 @@ public CellAst(XElement elem, List issues)
elem.GetFirstOrDefaultChildElement("value"),
"value",
issues);
+ FormulaRaw = formulaAttr?.Value;
StyleRefShortcut = styleRefAttr?.Value;
FormulaRef = formulaRefAttr?.Value;
FormulaRefScope = NormalizeFormulaRefScope(formulaRefScopeAttr?.Value, elem, issues);
- // Todo: ValueRaw から式のパース
}
private static string? NormalizeFormulaRefScope(string? rawScope, XElement owner, List issues)
diff --git a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs
index 5f724e1..8f9a18d 100644
--- a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs
+++ b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs
@@ -26,6 +26,14 @@ public sealed class UseAst : LayoutNodeAst, INamedAreaTarget
/// Gets or sets the with expr raw.
///
public string? WithExprRaw { get; init; }
+ ///
+ /// Gets the style overflow mode.
+ ///
+ public string StyleOverflow { get; init; } = "none";
+ ///
+ /// Gets a value indicating whether style overflow was explicitly specified.
+ ///
+ public bool HasStyleOverflowAttribute { get; init; }
///
/// コンポーネント参照先(解析フェーズで設定される)s
@@ -65,10 +73,33 @@ public UseAst(XElement elem, List issues)
var areaAttr = elem.Attribute("area");
var withAttr = elem.Attribute("with");
+ var styleOverflowAttr = elem.Attribute("styleOverflow");
ComponentName = nameAttr.Value;
AreaName = string.IsNullOrWhiteSpace(areaAttr?.Value) ? null : areaAttr.Value.Trim();
WithExprRaw = withAttr?.Value;
+ StyleOverflow = NormalizeStyleOverflow(styleOverflowAttr?.Value);
+ HasStyleOverflowAttribute = styleOverflowAttr is not null;
+ }
+
+ private static string NormalizeStyleOverflow(string? raw)
+ {
+ if (string.IsNullOrWhiteSpace(raw))
+ {
+ return "none";
+ }
+
+ if (string.Equals(raw, "none", StringComparison.OrdinalIgnoreCase))
+ {
+ return "none";
+ }
+
+ if (string.Equals(raw, "edge", StringComparison.OrdinalIgnoreCase))
+ {
+ return "edge";
+ }
+
+ return raw.Trim();
}
}
}
diff --git a/ExcelReport/ExcelReportLib/DSL/DslParser.cs b/ExcelReport/ExcelReportLib/DSL/DslParser.cs
index d1a6b04..9c5b15d 100644
--- a/ExcelReport/ExcelReportLib/DSL/DslParser.cs
+++ b/ExcelReport/ExcelReportLib/DSL/DslParser.cs
@@ -248,6 +248,8 @@ private static void ValidateDsl(WorkbookAst root, List issues, DslParserO
ValidateDuplicateSheetNames(root, issues);
ValidateStyleReferences(root, styleIndex, issues);
ValidateComponentReferences(root, componentIndex, issues);
+ ValidateCellContracts(root, issues);
+ ValidateUseContracts(root, issues);
ValidateRepeatConstraints(root, issues);
ValidateSheetConstraints(root, issues);
ValidateSheetOptions(root, issues);
@@ -569,6 +571,43 @@ private static void ValidateComponentReferences(
}
}
+ private static void ValidateCellContracts(WorkbookAst root, List issues)
+ {
+ foreach (var cell in EnumerateLayoutNodes(root).OfType())
+ {
+ if (!string.IsNullOrWhiteSpace(cell.ValueRaw) && !string.IsNullOrWhiteSpace(cell.FormulaRaw))
+ {
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.InvalidAttributeValue,
+ Message = " 要素で value 属性と formula 属性は同時に指定できません。",
+ Span = cell.Span,
+ });
+ }
+ }
+ }
+
+ private static void ValidateUseContracts(WorkbookAst root, List issues)
+ {
+ foreach (var use in EnumerateLayoutNodes(root).OfType())
+ {
+ if (string.Equals(use.StyleOverflow, "none", StringComparison.Ordinal) ||
+ string.Equals(use.StyleOverflow, "edge", StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.InvalidAttributeValue,
+ Message = $" |
CoordinateOutOfRange,
///
+ /// A template expansion exceeded the anchor range and emitted an overflow warning.
+ ///
+ TemplateRangeOverflow,
+ ///
+ /// An ExcelTemplate component range definition was malformed or pointed to the wrong sheet.
+ ///
+ InvalidComponentRange,
+ ///
+ /// An ExcelTemplate component range could not be inferred because it had no candidate cells.
+ ///
+ EmptyComponentRange,
+ ///
+ /// An ExcelTemplate merged cell crossed the resolved component boundary.
+ ///
+ MergedCellBoundaryViolation,
+ ///
+ /// The ExcelTemplate workbook used a feature that is intentionally unsupported in the initial release.
+ ///
+ UnsupportedExcelTemplateFeature,
+ ///
/// A formula reference series must be a single continuous one-dimensional range.
///
FormulaRefSeriesNot1DContinuous,
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs
new file mode 100644
index 0000000..f63885c
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs
@@ -0,0 +1,46 @@
+using System.Text;
+using System.Xml;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Emits DSL text from the normalized ExcelTemplate output contract.
+///
+public sealed class DslEmitter
+{
+ private readonly XmlTemplateSerializer xmlTemplateSerializer = new();
+
+ ///
+ /// Emits DSL-compatible XML text from the output contract.
+ ///
+ /// The normalized output contract.
+ /// The DSL text.
+ public string Emit(ExcelTemplateOutputContract contract)
+ {
+ ArgumentNullException.ThrowIfNull(contract);
+
+ var document = xmlTemplateSerializer.Serialize(contract);
+ var settings = new XmlWriterSettings
+ {
+ Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false),
+ Indent = true,
+ OmitXmlDeclaration = false,
+ NewLineChars = Environment.NewLine,
+ NewLineHandling = NewLineHandling.Replace,
+ };
+
+ using var stringWriter = new Utf8StringWriter();
+ using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
+ {
+ document.Save(xmlWriter);
+ }
+
+ return stringWriter.ToString();
+ }
+
+ private sealed class Utf8StringWriter : StringWriter
+ {
+ public override Encoding Encoding => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
+ }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs
new file mode 100644
index 0000000..98be39a
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs
@@ -0,0 +1,392 @@
+using System.Text;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Resolves component ranges from extracted Excel template workbooks.
+///
+public sealed class ExcelTemplateComponentRangeResolver
+{
+ private const string ComponentSheetPrefix = "__component_";
+ private const string ComponentRangeNamePrefix = "__component_range_";
+
+ ///
+ /// Resolves component ranges for all component sheets in the workbook.
+ ///
+ /// The extracted workbook.
+ /// The resolved ranges and issues.
+ public ExcelTemplateComponentRangeResolutionResult Resolve(ExcelTemplateWorkbook workbook)
+ {
+ ArgumentNullException.ThrowIfNull(workbook);
+
+ var ranges = new List();
+ var issues = new List();
+
+ foreach (var sheet in workbook.Sheets.Where(IsComponentSheet))
+ {
+ var componentName = sheet.Name[ComponentSheetPrefix.Length..];
+ var definedName = ComponentRangeNamePrefix + componentName;
+
+ if (workbook.DefinedNames.TryGetValue(definedName, out var explicitReference))
+ {
+ if (TryResolveExplicitRange(
+ sheet,
+ componentName,
+ explicitReference,
+ out var rangeReference,
+ out var explicitIssueKind,
+ out var explicitMessage))
+ {
+ ranges.Add(new ExcelTemplateComponentRange(componentName, sheet.Name, rangeReference));
+ }
+ else
+ {
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = explicitIssueKind,
+ Message = explicitMessage,
+ });
+ }
+
+ continue;
+ }
+
+ if (TryResolveAutoRange(sheet, out var autoReference))
+ {
+ ranges.Add(new ExcelTemplateComponentRange(componentName, sheet.Name, autoReference));
+ continue;
+ }
+
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.EmptyComponentRange,
+ Message = $"component '{componentName}' does not contain any candidate cells for range detection.",
+ });
+ }
+
+ return new ExcelTemplateComponentRangeResolutionResult(ranges, issues);
+ }
+
+ private static bool IsComponentSheet(ExcelTemplateSheet sheet) =>
+ sheet.Name.StartsWith(ComponentSheetPrefix, StringComparison.Ordinal) &&
+ sheet.Name.Length > ComponentSheetPrefix.Length;
+
+ private static bool TryResolveExplicitRange(
+ ExcelTemplateSheet sheet,
+ string componentName,
+ string explicitReference,
+ out string normalizedReference,
+ out IssueKind issueKind,
+ out string message)
+ {
+ normalizedReference = string.Empty;
+ issueKind = IssueKind.InvalidComponentRange;
+ message = string.Empty;
+
+ if (!TryParseSheetQualifiedRange(
+ explicitReference,
+ out var actualSheetName,
+ out var topRow,
+ out var leftColumn,
+ out var bottomRow,
+ out var rightColumn))
+ {
+ message = $"component '{componentName}' has invalid explicit range: {explicitReference}";
+ return false;
+ }
+
+ if (!string.Equals(sheet.Name, actualSheetName, StringComparison.Ordinal))
+ {
+ message = $"component '{componentName}' explicit range points to '{actualSheetName}' instead of '{sheet.Name}'.";
+ return false;
+ }
+
+ if (topRow <= 0 || leftColumn <= 0 || bottomRow < topRow || rightColumn < leftColumn)
+ {
+ message = $"component '{componentName}' has invalid explicit range: {explicitReference}";
+ return false;
+ }
+
+ if (!HasCandidateInRange(sheet, topRow, leftColumn, bottomRow, rightColumn))
+ {
+ issueKind = IssueKind.EmptyComponentRange;
+ message = $"component '{componentName}' explicit range does not contain any candidate cells.";
+ return false;
+ }
+
+ normalizedReference = ToRangeReference(topRow, leftColumn, bottomRow, rightColumn);
+ return true;
+ }
+
+ private static bool TryResolveAutoRange(
+ ExcelTemplateSheet sheet,
+ out string reference)
+ {
+ reference = string.Empty;
+
+ var minRow = int.MaxValue;
+ var minColumn = int.MaxValue;
+ var maxRow = 0;
+ var maxColumn = 0;
+
+ foreach (var cell in sheet.Cells.Where(IsCandidateCell))
+ {
+ minRow = Math.Min(minRow, cell.Row);
+ minColumn = Math.Min(minColumn, cell.Column);
+ maxRow = Math.Max(maxRow, cell.Row);
+ maxColumn = Math.Max(maxColumn, cell.Column);
+ }
+
+ foreach (var mergedRange in sheet.MergedRanges)
+ {
+ if (!TryParseLocalRange(mergedRange, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn))
+ {
+ continue;
+ }
+
+ minRow = Math.Min(minRow, topRow);
+ minColumn = Math.Min(minColumn, leftColumn);
+ maxRow = Math.Max(maxRow, bottomRow);
+ maxColumn = Math.Max(maxColumn, rightColumn);
+ }
+
+ if (maxRow == 0 || maxColumn == 0)
+ {
+ return false;
+ }
+
+ reference = ToRangeReference(minRow, minColumn, maxRow, maxColumn);
+ return true;
+ }
+
+ private static bool IsCandidateCell(ExcelTemplateCell cell) =>
+ !string.IsNullOrWhiteSpace(cell.Value) ||
+ !string.IsNullOrWhiteSpace(cell.Formula) ||
+ cell.Style is not null;
+
+ private static bool HasCandidateInRange(
+ ExcelTemplateSheet sheet,
+ int topRow,
+ int leftColumn,
+ int bottomRow,
+ int rightColumn)
+ {
+ if (sheet.Cells.Any(cell =>
+ IsCandidateCell(cell) &&
+ cell.Row >= topRow &&
+ cell.Row <= bottomRow &&
+ cell.Column >= leftColumn &&
+ cell.Column <= rightColumn))
+ {
+ return true;
+ }
+
+ foreach (var mergedRange in sheet.MergedRanges)
+ {
+ if (!TryParseLocalRange(mergedRange, out var mergedTopRow, out var mergedLeftColumn, out var mergedBottomRow, out var mergedRightColumn))
+ {
+ continue;
+ }
+
+ var intersects =
+ mergedBottomRow >= topRow &&
+ mergedTopRow <= bottomRow &&
+ mergedRightColumn >= leftColumn &&
+ mergedLeftColumn <= rightColumn;
+ if (intersects)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool TryParseSheetQualifiedRange(
+ string reference,
+ out string sheetName,
+ out int topRow,
+ out int leftColumn,
+ out int bottomRow,
+ out int rightColumn)
+ {
+ sheetName = string.Empty;
+ topRow = 0;
+ leftColumn = 0;
+ bottomRow = 0;
+ rightColumn = 0;
+
+ var separatorIndex = reference.LastIndexOf('!');
+ if (separatorIndex <= 0 || separatorIndex == reference.Length - 1)
+ {
+ return false;
+ }
+
+ sheetName = NormalizeSheetName(reference[..separatorIndex]);
+ if (string.IsNullOrWhiteSpace(sheetName))
+ {
+ return false;
+ }
+
+ return TryParseLocalRange(reference[(separatorIndex + 1)..], out topRow, out leftColumn, out bottomRow, out rightColumn);
+ }
+
+ private static string NormalizeSheetName(string token)
+ {
+ var trimmed = token.Trim();
+ if (trimmed.Length >= 2 && trimmed[0] == '\'' && trimmed[^1] == '\'')
+ {
+ return trimmed[1..^1].Replace("''", "'", StringComparison.Ordinal);
+ }
+
+ return trimmed;
+ }
+
+ private static bool TryParseLocalRange(
+ string reference,
+ out int topRow,
+ out int leftColumn,
+ out int bottomRow,
+ out int rightColumn)
+ {
+ topRow = 0;
+ leftColumn = 0;
+ bottomRow = 0;
+ rightColumn = 0;
+
+ if (string.IsNullOrWhiteSpace(reference) || reference.Contains(',', StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ var parts = reference.Split(':', StringSplitOptions.TrimEntries);
+ if (parts.Length is < 1 or > 2)
+ {
+ return false;
+ }
+
+ if (!TryParseCellReference(parts[0], out topRow, out leftColumn))
+ {
+ return false;
+ }
+
+ if (parts.Length == 1)
+ {
+ bottomRow = topRow;
+ rightColumn = leftColumn;
+ return true;
+ }
+
+ if (!TryParseCellReference(parts[1], out bottomRow, out rightColumn))
+ {
+ return false;
+ }
+
+ return bottomRow >= topRow && rightColumn >= leftColumn;
+ }
+
+ private static bool TryParseCellReference(string token, out int row, out int column)
+ {
+ row = 0;
+ column = 0;
+
+ if (string.IsNullOrWhiteSpace(token))
+ {
+ return false;
+ }
+
+ var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal);
+ var letters = new StringBuilder();
+ var digits = new StringBuilder();
+
+ foreach (var character in trimmed)
+ {
+ if (char.IsLetter(character))
+ {
+ if (digits.Length > 0)
+ {
+ return false;
+ }
+
+ letters.Append(char.ToUpperInvariant(character));
+ continue;
+ }
+
+ if (!char.IsDigit(character))
+ {
+ return false;
+ }
+
+ digits.Append(character);
+ }
+
+ if (letters.Length == 0 ||
+ digits.Length == 0 ||
+ !int.TryParse(digits.ToString(), out row))
+ {
+ return false;
+ }
+
+ column = 0;
+ foreach (var character in letters.ToString())
+ {
+ column = checked((column * 26) + (character - 'A' + 1));
+ }
+
+ return column > 0;
+ }
+
+ private static string ToRangeReference(int topRow, int leftColumn, int bottomRow, int rightColumn)
+ {
+ var start = ToCellReference(topRow, leftColumn);
+ var end = ToCellReference(bottomRow, rightColumn);
+ return start == end ? start : $"{start}:{end}";
+ }
+
+ private static string ToCellReference(int row, int column)
+ {
+ var current = column;
+ var builder = new StringBuilder();
+ while (current > 0)
+ {
+ current--;
+ builder.Insert(0, (char)('A' + (current % 26)));
+ current /= 26;
+ }
+
+ return builder.Append(row).ToString();
+ }
+}
+
+///
+/// Represents component range resolution output.
+///
+public sealed class ExcelTemplateComponentRangeResolutionResult
+{
+ ///
+ /// Initializes a new instance of the resolution result.
+ ///
+ /// The resolved component ranges.
+ /// The collected issues.
+ public ExcelTemplateComponentRangeResolutionResult(
+ IReadOnlyList? ranges = null,
+ IReadOnlyList? issues = null)
+ {
+ Ranges = ranges?.ToArray() ?? [];
+ Issues = issues?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the resolved ranges.
+ ///
+ public IReadOnlyList Ranges { get; }
+
+ ///
+ /// Gets the collected issues.
+ ///
+ public IReadOnlyList Issues { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs
new file mode 100644
index 0000000..a9e6671
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs
@@ -0,0 +1,30 @@
+using ExcelReportLib.DSL;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Represents the result of converting an ExcelTemplate workbook to text.
+///
+public sealed class ExcelTemplateConversionResult
+{
+ ///
+ /// Initializes a new instance of the conversion result.
+ ///
+ /// The emitted text.
+ /// The aggregated issues.
+ public ExcelTemplateConversionResult(string text, IReadOnlyList? issues = null)
+ {
+ Text = text ?? string.Empty;
+ Issues = issues?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the emitted text.
+ ///
+ public string Text { get; }
+
+ ///
+ /// Gets the aggregated issues.
+ ///
+ public IReadOnlyList Issues { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs
new file mode 100644
index 0000000..9e7493c
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs
@@ -0,0 +1,12 @@
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Represents options for ExcelTemplate conversion-only APIs.
+///
+public sealed class ExcelTemplateConvertOptions
+{
+ ///
+ /// Gets or sets a value indicating whether emitted text should be validated against the DSL schema.
+ ///
+ public bool EnableSchemaValidation { get; init; } = true;
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs
new file mode 100644
index 0000000..88435a0
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs
@@ -0,0 +1,107 @@
+using ExcelReportLib.DSL;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Converts ExcelTemplate xlsx workbooks into DSL-compatible XML text outputs.
+///
+public sealed class ExcelTemplateConverter
+{
+ private readonly ExcelTemplateExtractor extractor = new();
+ private readonly ExcelTemplateOutputContractBuilder contractBuilder = new();
+ private readonly XmlTemplateSerializer xmlTemplateSerializer = new();
+ private readonly DslEmitter dslEmitter = new();
+
+ ///
+ /// Converts an xlsx workbook to DSL text.
+ ///
+ /// The source xlsx file path.
+ /// Optional conversion settings.
+ /// The conversion result.
+ public ExcelTemplateConversionResult ConvertToDsl(string xlsxPath, ExcelTemplateConvertOptions? options = null)
+ {
+ return ConvertInternal(
+ xlsxPath,
+ contract => dslEmitter.Emit(contract),
+ options);
+ }
+
+ ///
+ /// Converts an xlsx workbook to DSL-compatible XML debug text.
+ ///
+ /// The source xlsx file path.
+ /// Optional conversion settings.
+ /// The conversion result.
+ public ExcelTemplateConversionResult ConvertToXmlTemplate(string xlsxPath, ExcelTemplateConvertOptions? options = null)
+ {
+ return ConvertInternal(
+ xlsxPath,
+ contract => xmlTemplateSerializer.Serialize(contract).ToString(),
+ options);
+ }
+
+ private ExcelTemplateConversionResult ConvertInternal(
+ string xlsxPath,
+ Func emitter,
+ ExcelTemplateConvertOptions? options)
+ {
+ var effectiveOptions = options ?? new ExcelTemplateConvertOptions();
+ var issues = new List();
+
+ if (string.IsNullOrWhiteSpace(xlsxPath))
+ {
+ issues.Add(CreateLoadIssue("ExcelTemplate xlsx path is required."));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+
+ if (!File.Exists(xlsxPath))
+ {
+ issues.Add(CreateLoadIssue($"ExcelTemplate file not found: {xlsxPath}"));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+
+ try
+ {
+ var workbook = extractor.Extract(xlsxPath);
+ var contract = contractBuilder.Build(workbook);
+ issues.AddRange(contract.Issues);
+
+ var text = emitter(contract);
+
+ var parseResult = DslParser.ParseFromText(
+ text,
+ new DslParserOptions { EnableSchemaValidation = effectiveOptions.EnableSchemaValidation });
+ issues.AddRange(parseResult.Issues);
+
+ return new ExcelTemplateConversionResult(text, issues);
+ }
+ catch (IOException ex)
+ {
+ issues.Add(CreateLoadIssue(ex.Message));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+ catch (InvalidDataException ex)
+ {
+ issues.Add(CreateLoadIssue(ex.Message));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+ catch (FileFormatException ex)
+ {
+ issues.Add(CreateLoadIssue(ex.Message));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+ catch (UnauthorizedAccessException ex)
+ {
+ issues.Add(CreateLoadIssue(ex.Message));
+ return new ExcelTemplateConversionResult(string.Empty, issues);
+ }
+ }
+
+ private static Issue CreateLoadIssue(string message) =>
+ new()
+ {
+ Severity = IssueSeverity.Fatal,
+ Kind = IssueKind.LoadFile,
+ Message = message,
+ };
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs
new file mode 100644
index 0000000..18456c6
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs
@@ -0,0 +1,48 @@
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Normalizes ExcelTemplate expression shorthand into DSL runtime-compatible expression text.
+///
+internal static class ExcelTemplateExpressionNormalizer
+{
+ ///
+ /// Normalizes an ExcelTemplate expression when it uses the shorthand @foo form.
+ ///
+ /// The raw ExcelTemplate expression text.
+ /// Known local repeat variable names.
+ /// The normalized expression text.
+ public static string? Normalize(string? expression, IReadOnlySet? localVariableNames = null)
+ {
+ if (string.IsNullOrWhiteSpace(expression))
+ {
+ return expression;
+ }
+
+ var trimmed = expression.Trim();
+ if (!trimmed.StartsWith('@') || trimmed.StartsWith("@(", StringComparison.Ordinal))
+ {
+ return expression;
+ }
+
+ var body = trimmed[1..].Trim();
+ if (string.IsNullOrWhiteSpace(body))
+ {
+ return expression;
+ }
+
+ if (IsSimpleIdentifier(body))
+ {
+ if (localVariableNames?.Contains(body) == true)
+ {
+ return "@(" + body + ")";
+ }
+
+ return "@(root." + char.ToUpperInvariant(body[0]) + body[1..] + ")";
+ }
+
+ return "@(" + body + ")";
+ }
+
+ private static bool IsSimpleIdentifier(string value) =>
+ value.Length > 0 && value.All(character => char.IsLetterOrDigit(character) || character == '_');
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs
new file mode 100644
index 0000000..fe49807
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs
@@ -0,0 +1,187 @@
+using System.Text;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Reads an Excel workbook into the ExcelTemplate intermediate model.
+///
+public sealed class ExcelTemplateExtractor
+{
+ ///
+ /// Extracts workbook metadata, sheets, cells, defined names, and merged ranges from an xlsx file.
+ ///
+ /// The source xlsx file path.
+ /// The extracted workbook model.
+ public ExcelTemplateWorkbook Extract(string xlsxPath)
+ {
+ if (string.IsNullOrWhiteSpace(xlsxPath))
+ {
+ throw new ArgumentException("xlsxPath is required.", nameof(xlsxPath));
+ }
+
+ if (!File.Exists(xlsxPath))
+ {
+ throw new FileNotFoundException($"Excel template file not found: {xlsxPath}", xlsxPath);
+ }
+
+ using var document = SpreadsheetDocument.Open(xlsxPath, false);
+ var workbookPart = document.WorkbookPart
+ ?? throw new InvalidDataException("WorkbookPart was not found.");
+ var workbook = workbookPart.Workbook
+ ?? throw new InvalidDataException("Workbook root was not found.");
+
+ var sheets = workbook.Sheets?.Elements()
+ .Select(sheet => ExtractSheet(workbookPart, sheet))
+ .ToArray() ?? [];
+ var definedNames = ExtractDefinedNames(workbook);
+
+ return new ExcelTemplateWorkbook(sheets, definedNames);
+ }
+
+ private static ExcelTemplateSheet ExtractSheet(WorkbookPart workbookPart, Sheet sheet)
+ {
+ var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id!);
+ var worksheet = worksheetPart.Worksheet;
+
+ var cells = worksheet.Descendants()
+ .Select(cell => ExtractCell(workbookPart, cell))
+ .OrderBy(cell => cell.Row)
+ .ThenBy(cell => cell.Column)
+ .ToArray();
+ var mergedRanges = worksheet.Elements()
+ .SelectMany(mergeCells => mergeCells.Elements())
+ .Select(mergeCell => mergeCell.Reference?.Value)
+ .Where(reference => !string.IsNullOrWhiteSpace(reference))
+ .Cast()
+ .ToArray();
+ var hasConditionalFormatting = worksheet.Elements().Any();
+
+ return new ExcelTemplateSheet(sheet.Name?.Value ?? string.Empty, cells, mergedRanges, hasConditionalFormatting);
+ }
+
+ private static ExcelTemplateCell ExtractCell(WorkbookPart workbookPart, Cell cell)
+ {
+ var reference = cell.CellReference?.Value ?? string.Empty;
+ if (!TryParseCellReference(reference, out var row, out var column))
+ {
+ throw new InvalidDataException($"Unsupported cell reference: {reference}");
+ }
+
+ var formula = cell.CellFormula?.Text;
+ var value = formula is null ? ReadCellValue(workbookPart, cell) : null;
+ var style = cell.StyleIndex is not null
+ ? new ExcelTemplateStyle(cell.StyleIndex.Value)
+ : null;
+
+ return new ExcelTemplateCell(reference, (int)row, (int)column, value, formula, style);
+ }
+
+ private static IReadOnlyDictionary ExtractDefinedNames(Workbook workbook)
+ {
+ var definedNames = new Dictionary(StringComparer.Ordinal);
+ foreach (var definedName in workbook.DefinedNames?.Elements() ?? [])
+ {
+ var name = definedName.Name?.Value;
+ if (string.IsNullOrWhiteSpace(name))
+ {
+ continue;
+ }
+
+ definedNames[name] = definedName.Text ?? string.Empty;
+ }
+
+ return definedNames;
+ }
+
+ private static string? ReadCellValue(WorkbookPart workbookPart, Cell cell)
+ {
+ if (cell.DataType?.Value == CellValues.InlineString)
+ {
+ return cell.InlineString?.InnerText ?? string.Empty;
+ }
+
+ if (cell.DataType?.Value == CellValues.SharedString)
+ {
+ var sharedStringIndex = cell.CellValue?.Text;
+ if (sharedStringIndex is null ||
+ !int.TryParse(sharedStringIndex, out var index) ||
+ workbookPart.SharedStringTablePart?.SharedStringTable is null)
+ {
+ return string.Empty;
+ }
+
+ return workbookPart.SharedStringTablePart.SharedStringTable.Elements()
+ .ElementAt(index)
+ .InnerText;
+ }
+
+ return cell.CellValue?.Text;
+ }
+
+ private static bool TryParseCellReference(string reference, out uint row, out uint column)
+ {
+ if (string.IsNullOrWhiteSpace(reference))
+ {
+ row = 0;
+ column = 0;
+ return false;
+ }
+
+ var trimmed = reference.Trim().TrimStart('$');
+ var letters = new StringBuilder();
+ var digits = new StringBuilder();
+
+ foreach (var character in trimmed)
+ {
+ if (char.IsLetter(character))
+ {
+ if (digits.Length > 0)
+ {
+ row = 0;
+ column = 0;
+ return false;
+ }
+
+ letters.Append(char.ToUpperInvariant(character));
+ continue;
+ }
+
+ if (char.IsDigit(character))
+ {
+ digits.Append(character);
+ continue;
+ }
+
+ if (character != '$')
+ {
+ row = 0;
+ column = 0;
+ return false;
+ }
+ }
+
+ if (letters.Length == 0 || digits.Length == 0 || !uint.TryParse(digits.ToString(), out row))
+ {
+ row = 0;
+ column = 0;
+ return false;
+ }
+
+ column = ColumnNameToIndex(letters.ToString());
+ return column > 0;
+ }
+
+ private static uint ColumnNameToIndex(string columnName)
+ {
+ uint value = 0;
+ foreach (var character in columnName)
+ {
+ value = checked((value * 26) + (uint)(character - 'A' + 1));
+ }
+
+ return value;
+ }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs
new file mode 100644
index 0000000..31cda5d
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs
@@ -0,0 +1,19 @@
+using ExcelReportLib.Logger;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Represents options for end-to-end ExcelTemplate report generation.
+///
+public sealed class ExcelTemplateGenerateOptions
+{
+ ///
+ /// Gets or sets conversion options for the ExcelTemplate-to-DSL step.
+ ///
+ public ExcelTemplateConvertOptions? ConvertOptions { get; init; }
+
+ ///
+ /// Gets or sets report generation options for the DSL-to-XLSX step.
+ ///
+ public ReportGeneratorOptions? ReportGeneratorOptions { get; init; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs
new file mode 100644
index 0000000..949b4c9
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs
@@ -0,0 +1,329 @@
+using System.Text;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Builds the normalized conversion output contract used by ExcelTemplate serializers and emitters.
+///
+public sealed class ExcelTemplateOutputContractBuilder
+{
+ private const string ComponentSheetPrefix = "__component_";
+ private static readonly IReadOnlySet EmptyVariableNames = new HashSet(StringComparer.Ordinal);
+ private readonly ExcelTemplateComponentRangeResolver componentRangeResolver = new();
+ private readonly ExcelTemplateValidator validator = new();
+ private readonly UseTriggerParser useTriggerParser = new();
+
+ ///
+ /// Builds the conversion output contract from an extracted workbook.
+ ///
+ /// The extracted workbook.
+ /// The normalized contract.
+ public ExcelTemplateOutputContract Build(ExcelTemplateWorkbook workbook)
+ {
+ ArgumentNullException.ThrowIfNull(workbook);
+
+ var rangeResolution = componentRangeResolver.Resolve(workbook);
+ var validation = validator.Validate(workbook, rangeResolution.Ranges);
+ var variableScope = ResolveComponentVariableScopes(workbook);
+ var aggregatedIssues = rangeResolution.Issues
+ .Concat(validation.Issues)
+ .Concat(variableScope.Issues)
+ .ToArray();
+ var rangesBySheet = rangeResolution.Ranges.ToDictionary(range => range.SheetName, StringComparer.Ordinal);
+
+ var components = workbook.Sheets
+ .Where(IsComponentSheet)
+ .Select(sheet =>
+ {
+ var hasRange = rangesBySheet.TryGetValue(sheet.Name, out var range);
+ var componentName = sheet.Name[ComponentSheetPrefix.Length..];
+ var valueVariableNames = variableScope.ComponentVariableNames.TryGetValue(componentName, out var variables)
+ ? variables
+ : EmptyVariableNames;
+ return new ExcelTemplateOutputComponent(
+ componentName,
+ sheet.Name,
+ hasRange ? range!.Reference : null,
+ hasRange,
+ BuildItems(sheet, hasRange ? range!.Reference : null, valueVariableNames));
+ })
+ .ToArray();
+
+ var sheets = workbook.Sheets
+ .Where(sheet => !IsComponentSheet(sheet))
+ .Select(sheet => new ExcelTemplateOutputSheet(sheet.Name, BuildItems(sheet, rangeReference: null, EmptyVariableNames)))
+ .ToArray();
+
+ return new ExcelTemplateOutputContract(components, sheets, aggregatedIssues);
+ }
+
+ private IReadOnlyList BuildItems(
+ ExcelTemplateSheet sheet,
+ string? rangeReference,
+ IReadOnlySet localVariableNames)
+ {
+ var filter = TryParseRange(rangeReference, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn);
+ var items = new List();
+
+ foreach (var cell in sheet.Cells
+ .OrderBy(candidate => candidate.Row)
+ .ThenBy(candidate => candidate.Column))
+ {
+ if (filter && !IsWithinRange(cell, topRow, leftColumn, bottomRow, rightColumn))
+ {
+ continue;
+ }
+
+ items.Add(NormalizeItem(cell, localVariableNames));
+ }
+
+ return items;
+ }
+
+ private ExcelTemplateOutputItem NormalizeItem(ExcelTemplateCell cell, IReadOnlySet localVariableNames)
+ {
+ var styleIndex = cell.Style?.Index;
+ var triggerResult = useTriggerParser.Parse(cell.Value);
+
+ if (!triggerResult.IsTrigger || triggerResult.Trigger is null)
+ {
+ return new ExcelTemplateOutputCell(
+ cell.Reference,
+ cell.Row,
+ cell.Column,
+ styleIndex,
+ ExcelTemplateExpressionNormalizer.Normalize(cell.Value, localVariableNames),
+ cell.Formula);
+ }
+
+ if (string.IsNullOrWhiteSpace(triggerResult.Trigger.FromExpression))
+ {
+ return new ExcelTemplateOutputUse(
+ cell.Reference,
+ cell.Row,
+ cell.Column,
+ styleIndex,
+ triggerResult.Trigger.ComponentName,
+ triggerResult.Trigger.StyleOverflow);
+ }
+
+ return new ExcelTemplateOutputRepeatUse(
+ cell.Reference,
+ cell.Row,
+ cell.Column,
+ styleIndex,
+ triggerResult.Trigger.ComponentName,
+ ExcelTemplateExpressionNormalizer.Normalize(triggerResult.Trigger.FromExpression)!,
+ triggerResult.Trigger.VariableName!,
+ triggerResult.Trigger.RepeatDirection ?? "down",
+ triggerResult.Trigger.StyleOverflow);
+ }
+
+ private ComponentVariableScopeResolution ResolveComponentVariableScopes(ExcelTemplateWorkbook workbook)
+ {
+ var discoveredVariables = new Dictionary>(StringComparer.Ordinal);
+ var componentsWithSimpleShorthand = CollectComponentsWithSimpleShorthand(workbook);
+ var issues = new List();
+ var componentVariableNames = new Dictionary>(StringComparer.Ordinal);
+
+ foreach (var cell in workbook.Sheets.SelectMany(sheet => sheet.Cells))
+ {
+ var triggerResult = useTriggerParser.Parse(cell.Value);
+ if (!triggerResult.IsTrigger ||
+ triggerResult.Trigger is null ||
+ string.IsNullOrWhiteSpace(triggerResult.Trigger.ComponentName) ||
+ string.IsNullOrWhiteSpace(triggerResult.Trigger.VariableName))
+ {
+ continue;
+ }
+
+ if (!discoveredVariables.TryGetValue(triggerResult.Trigger.ComponentName, out var variableNames))
+ {
+ variableNames = new HashSet(StringComparer.Ordinal);
+ discoveredVariables[triggerResult.Trigger.ComponentName] = variableNames;
+ }
+
+ variableNames.Add(triggerResult.Trigger.VariableName);
+ }
+
+ foreach (var discovered in discoveredVariables)
+ {
+ if (discovered.Value.Count == 1)
+ {
+ componentVariableNames[discovered.Key] = discovered.Value;
+ continue;
+ }
+
+ componentVariableNames[discovered.Key] = EmptyVariableNames;
+ if (componentsWithSimpleShorthand.Contains(discovered.Key))
+ {
+ issues.Add(
+ new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.InvalidAttributeValue,
+ Message = $"component '{discovered.Key}' is referenced by multiple repeat variables ({string.Join(", ", discovered.Value.OrderBy(value => value, StringComparer.Ordinal))}); simple shorthand local variable normalization is ambiguous.",
+ });
+ }
+ }
+
+ return new ComponentVariableScopeResolution(componentVariableNames, issues);
+ }
+
+ private HashSet CollectComponentsWithSimpleShorthand(ExcelTemplateWorkbook workbook)
+ {
+ var components = new HashSet(StringComparer.Ordinal);
+
+ foreach (var sheet in workbook.Sheets.Where(IsComponentSheet))
+ {
+ var componentName = sheet.Name[ComponentSheetPrefix.Length..];
+ var hasSimpleShorthand = sheet.Cells.Any(
+ cell =>
+ {
+ var triggerResult = useTriggerParser.Parse(cell.Value);
+ return (!triggerResult.IsTrigger || triggerResult.Trigger is null) && IsSimpleShorthandExpression(cell.Value);
+ });
+ if (hasSimpleShorthand)
+ {
+ components.Add(componentName);
+ }
+ }
+
+ return components;
+ }
+
+ private static bool IsSimpleShorthandExpression(string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ return false;
+ }
+
+ var trimmed = value.Trim();
+ if (!trimmed.StartsWith('@') || trimmed.StartsWith("@(", StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ var body = trimmed[1..].Trim();
+ return body.Length > 0 && body.All(character => char.IsLetterOrDigit(character) || character == '_');
+ }
+
+ private sealed class ComponentVariableScopeResolution
+ {
+ public ComponentVariableScopeResolution(
+ IReadOnlyDictionary> componentVariableNames,
+ IReadOnlyList issues)
+ {
+ ComponentVariableNames = componentVariableNames;
+ Issues = issues;
+ }
+
+ public IReadOnlyDictionary> ComponentVariableNames { get; }
+
+ public IReadOnlyList Issues { get; }
+ }
+
+ private static bool IsComponentSheet(ExcelTemplateSheet sheet) =>
+ sheet.Name.StartsWith(ComponentSheetPrefix, StringComparison.Ordinal) &&
+ sheet.Name.Length > ComponentSheetPrefix.Length;
+
+ private static bool IsWithinRange(
+ ExcelTemplateCell cell,
+ int topRow,
+ int leftColumn,
+ int bottomRow,
+ int rightColumn) =>
+ cell.Row >= topRow &&
+ cell.Row <= bottomRow &&
+ cell.Column >= leftColumn &&
+ cell.Column <= rightColumn;
+
+ private static bool TryParseRange(
+ string? reference,
+ out int topRow,
+ out int leftColumn,
+ out int bottomRow,
+ out int rightColumn)
+ {
+ topRow = 0;
+ leftColumn = 0;
+ bottomRow = 0;
+ rightColumn = 0;
+
+ if (string.IsNullOrWhiteSpace(reference))
+ {
+ return false;
+ }
+
+ var tokens = reference.Split(':', StringSplitOptions.TrimEntries);
+ if (tokens.Length is < 1 or > 2 || !TryParseCellReference(tokens[0], out topRow, out leftColumn))
+ {
+ return false;
+ }
+
+ if (tokens.Length == 1)
+ {
+ bottomRow = topRow;
+ rightColumn = leftColumn;
+ return true;
+ }
+
+ if (!TryParseCellReference(tokens[1], out bottomRow, out rightColumn))
+ {
+ return false;
+ }
+
+ return bottomRow >= topRow && rightColumn >= leftColumn;
+ }
+
+ private static bool TryParseCellReference(string token, out int row, out int column)
+ {
+ row = 0;
+ column = 0;
+
+ if (string.IsNullOrWhiteSpace(token))
+ {
+ return false;
+ }
+
+ var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal);
+ var letters = new StringBuilder();
+ var digits = new StringBuilder();
+
+ foreach (var character in trimmed)
+ {
+ if (char.IsLetter(character))
+ {
+ if (digits.Length > 0)
+ {
+ return false;
+ }
+
+ letters.Append(char.ToUpperInvariant(character));
+ continue;
+ }
+
+ if (!char.IsDigit(character))
+ {
+ return false;
+ }
+
+ digits.Append(character);
+ }
+
+ if (letters.Length == 0 || digits.Length == 0 || !int.TryParse(digits.ToString(), out row))
+ {
+ return false;
+ }
+
+ foreach (var character in letters.ToString())
+ {
+ column = checked((column * 26) + (character - 'A' + 1));
+ }
+
+ return column > 0;
+ }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs
new file mode 100644
index 0000000..cda52e6
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs
@@ -0,0 +1,98 @@
+using ExcelReportLib.DSL;
+using ExcelReportLib.Logger;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Generates final XLSX output directly from an ExcelTemplate workbook.
+///
+public sealed class ExcelTemplateReportGenerator
+{
+ private readonly ExcelTemplateConverter converter;
+ private readonly ReportGenerator reportGenerator;
+
+ ///
+ /// Initializes a new instance of the report generator facade.
+ ///
+ /// The ExcelTemplate converter.
+ /// The downstream DSL report generator.
+ public ExcelTemplateReportGenerator(
+ ExcelTemplateConverter? converter = null,
+ ReportGenerator? reportGenerator = null)
+ {
+ this.converter = converter ?? new ExcelTemplateConverter();
+ this.reportGenerator = reportGenerator ?? new ReportGenerator();
+ }
+
+ ///
+ /// Converts an ExcelTemplate workbook to DSL and renders the final XLSX through the existing report pipeline.
+ ///
+ /// The source xlsx path.
+ /// The data object used by the DSL runtime.
+ /// Optional generation settings.
+ /// The cancellation token.
+ /// The aggregated report generation result.
+ public ReportGeneratorResult GenerateFromExcelTemplate(
+ string xlsxPath,
+ object? data,
+ ExcelTemplateGenerateOptions? options = null,
+ CancellationToken cancellationToken = default)
+ {
+ var effectiveOptions = options ?? new ExcelTemplateGenerateOptions();
+ var reportOptions = effectiveOptions.ReportGeneratorOptions ?? new ReportGeneratorOptions();
+ var logger = reportOptions.Logger ?? new ReportLogger();
+ var reportOptionsWithLogger = EnsureLogger(reportOptions, logger);
+
+ var conversionResult = converter.ConvertToDsl(xlsxPath, effectiveOptions.ConvertOptions);
+ LogIssues(logger, conversionResult.Issues);
+
+ if (HasFatal(conversionResult.Issues) || string.IsNullOrWhiteSpace(conversionResult.Text))
+ {
+ return new ReportGeneratorResult(
+ renderResult: null,
+ issues: conversionResult.Issues,
+ logEntries: logger.GetEntries(),
+ abortedByFatal: true);
+ }
+
+ var reportResult = reportGenerator.Generate(
+ conversionResult.Text,
+ data,
+ reportOptionsWithLogger,
+ cancellationToken);
+
+ return new ReportGeneratorResult(
+ reportResult.RenderResult,
+ conversionResult.Issues.Concat(reportResult.Issues).ToArray(),
+ reportResult.LogEntries,
+ reportResult.AbortedByFatal,
+ reportResult.UnhandledException);
+ }
+
+ private static ReportGeneratorOptions EnsureLogger(ReportGeneratorOptions options, IReportLogger logger)
+ {
+ if (ReferenceEquals(options.Logger, logger))
+ {
+ return options;
+ }
+
+ return new ReportGeneratorOptions
+ {
+ EnableSchemaValidation = options.EnableSchemaValidation,
+ TreatExpressionSyntaxErrorAsFatal = options.TreatExpressionSyntaxErrorAsFatal,
+ Logger = logger,
+ RenderOptions = options.RenderOptions,
+ };
+ }
+
+ private static bool HasFatal(IEnumerable issues) =>
+ issues.Any(issue => issue.Severity == IssueSeverity.Fatal);
+
+ private static void LogIssues(IReportLogger logger, IEnumerable issues)
+ {
+ foreach (var issue in issues)
+ {
+ logger.LogIssue(issue, ReportPhase.Parsing);
+ }
+ }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs
new file mode 100644
index 0000000..4b4b3b3
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs
@@ -0,0 +1,245 @@
+using System.Text;
+using ExcelReportLib.DSL;
+using ExcelReportLib.ExcelTemplate.Model;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Validates extracted ExcelTemplate workbooks against initial-release constraints.
+///
+public sealed class ExcelTemplateValidator
+{
+ private readonly UseTriggerParser useTriggerParser = new();
+
+ ///
+ /// Validates the workbook and resolved component ranges.
+ ///
+ /// The extracted workbook.
+ /// The resolved component ranges.
+ /// The validation result.
+ public ExcelTemplateValidationResult Validate(
+ ExcelTemplateWorkbook workbook,
+ IReadOnlyList componentRanges)
+ {
+ ArgumentNullException.ThrowIfNull(workbook);
+ ArgumentNullException.ThrowIfNull(componentRanges);
+
+ var issues = new List();
+ var rangesBySheet = componentRanges.ToDictionary(range => range.SheetName, StringComparer.Ordinal);
+ var componentNames = new HashSet(componentRanges.Select(range => range.ComponentName), StringComparer.Ordinal);
+
+ foreach (var sheet in workbook.Sheets)
+ {
+ ValidateUnsupportedFeatures(sheet, issues);
+ ValidateUseTriggers(sheet, componentNames, issues);
+
+ if (rangesBySheet.TryGetValue(sheet.Name, out var componentRange))
+ {
+ ValidateMergedRanges(sheet, componentRange, issues);
+ }
+ }
+
+ return new ExcelTemplateValidationResult(issues);
+ }
+
+ private void ValidateUnsupportedFeatures(ExcelTemplateSheet sheet, IList issues)
+ {
+ if (!sheet.HasConditionalFormatting)
+ {
+ return;
+ }
+
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.UnsupportedExcelTemplateFeature,
+ Message = $"sheet '{sheet.Name}' uses conditional formatting, which is unsupported in the initial ExcelTemplate release.",
+ });
+ }
+
+ private void ValidateUseTriggers(
+ ExcelTemplateSheet sheet,
+ ISet componentNames,
+ IList issues)
+ {
+ foreach (var cell in sheet.Cells)
+ {
+ var result = useTriggerParser.Parse(cell.Value);
+ if (!result.IsTrigger)
+ {
+ continue;
+ }
+
+ if (result.Issues.Count > 0)
+ {
+ foreach (var issue in result.Issues)
+ {
+ issues.Add(new Issue
+ {
+ Severity = issue.Severity,
+ Kind = issue.Kind,
+ Message = $"sheet '{sheet.Name}' cell {cell.Reference}: {issue.Message}",
+ });
+ }
+
+ continue;
+ }
+
+ if (result.Trigger is not null && !componentNames.Contains(result.Trigger.ComponentName))
+ {
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.UndefinedComponent,
+ Message = $"sheet '{sheet.Name}' cell {cell.Reference} references undefined component '{result.Trigger.ComponentName}'.",
+ });
+ }
+ }
+ }
+
+ private static void ValidateMergedRanges(
+ ExcelTemplateSheet sheet,
+ ExcelTemplateComponentRange componentRange,
+ IList issues)
+ {
+ if (!TryParseRangeReference(componentRange.Reference, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn))
+ {
+ return;
+ }
+
+ foreach (var mergedRange in sheet.MergedRanges)
+ {
+ if (!TryParseRangeReference(mergedRange, out var mergedTop, out var mergedLeft, out var mergedBottom, out var mergedRight))
+ {
+ continue;
+ }
+
+ var intersects =
+ mergedBottom >= topRow &&
+ mergedTop <= bottomRow &&
+ mergedRight >= leftColumn &&
+ mergedLeft <= rightColumn;
+ var contained =
+ mergedTop >= topRow &&
+ mergedBottom <= bottomRow &&
+ mergedLeft >= leftColumn &&
+ mergedRight <= rightColumn;
+
+ if (intersects && !contained)
+ {
+ issues.Add(new Issue
+ {
+ Severity = IssueSeverity.Error,
+ Kind = IssueKind.MergedCellBoundaryViolation,
+ Message = $"component sheet '{sheet.Name}' has merged range '{mergedRange}' crossing resolved component range '{componentRange.Reference}'.",
+ });
+ }
+ }
+ }
+
+ private static bool TryParseRangeReference(
+ string reference,
+ out int topRow,
+ out int leftColumn,
+ out int bottomRow,
+ out int rightColumn)
+ {
+ topRow = 0;
+ leftColumn = 0;
+ bottomRow = 0;
+ rightColumn = 0;
+
+ if (string.IsNullOrWhiteSpace(reference) || reference.Contains(',', StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ var parts = reference.Split(':', StringSplitOptions.TrimEntries);
+ if (parts.Length is < 1 or > 2 || !TryParseCellReference(parts[0], out topRow, out leftColumn))
+ {
+ return false;
+ }
+
+ if (parts.Length == 1)
+ {
+ bottomRow = topRow;
+ rightColumn = leftColumn;
+ return true;
+ }
+
+ if (!TryParseCellReference(parts[1], out bottomRow, out rightColumn))
+ {
+ return false;
+ }
+
+ return bottomRow >= topRow && rightColumn >= leftColumn;
+ }
+
+ private static bool TryParseCellReference(string token, out int row, out int column)
+ {
+ row = 0;
+ column = 0;
+
+ if (string.IsNullOrWhiteSpace(token))
+ {
+ return false;
+ }
+
+ var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal);
+ var letters = new StringBuilder();
+ var digits = new StringBuilder();
+
+ foreach (var character in trimmed)
+ {
+ if (char.IsLetter(character))
+ {
+ if (digits.Length > 0)
+ {
+ return false;
+ }
+
+ letters.Append(char.ToUpperInvariant(character));
+ continue;
+ }
+
+ if (!char.IsDigit(character))
+ {
+ return false;
+ }
+
+ digits.Append(character);
+ }
+
+ if (letters.Length == 0 || digits.Length == 0 || !int.TryParse(digits.ToString(), out row))
+ {
+ return false;
+ }
+
+ foreach (var character in letters.ToString())
+ {
+ column = checked((column * 26) + (character - 'A' + 1));
+ }
+
+ return column > 0;
+ }
+}
+
+///
+/// Represents ExcelTemplate validation output.
+///
+public sealed class ExcelTemplateValidationResult
+{
+ ///
+ /// Initializes a new instance of the validation result.
+ ///
+ /// The collected issues.
+ public ExcelTemplateValidationResult(IReadOnlyList? issues = null)
+ {
+ Issues = issues?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the collected issues.
+ ///
+ public IReadOnlyList Issues { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs
new file mode 100644
index 0000000..35447bf
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs
@@ -0,0 +1,62 @@
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents an extracted Excel template cell.
+///
+public sealed class ExcelTemplateCell
+{
+ ///
+ /// Initializes a new instance of the cell model.
+ ///
+ /// The A1 reference.
+ /// The 1-based row index.
+ /// The 1-based column index.
+ /// The cell value.
+ /// The cell formula text without leading equals.
+ /// The cell style metadata.
+ public ExcelTemplateCell(
+ string reference,
+ int row,
+ int column,
+ string? value,
+ string? formula,
+ ExcelTemplateStyle? style)
+ {
+ Reference = reference;
+ Row = row;
+ Column = column;
+ Value = value;
+ Formula = formula;
+ Style = style;
+ }
+
+ ///
+ /// Gets the A1 reference.
+ ///
+ public string Reference { get; }
+
+ ///
+ /// Gets the 1-based row index.
+ ///
+ public int Row { get; }
+
+ ///
+ /// Gets the 1-based column index.
+ ///
+ public int Column { get; }
+
+ ///
+ /// Gets the cell value.
+ ///
+ public string? Value { get; }
+
+ ///
+ /// Gets the formula text.
+ ///
+ public string? Formula { get; }
+
+ ///
+ /// Gets the extracted style metadata.
+ ///
+ public ExcelTemplateStyle? Style { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs
new file mode 100644
index 0000000..2466124
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs
@@ -0,0 +1,35 @@
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents a resolved component range in an Excel template workbook.
+///
+public sealed class ExcelTemplateComponentRange
+{
+ ///
+ /// Initializes a new instance of the component range model.
+ ///
+ /// The logical component name.
+ /// The source sheet name.
+ /// The A1 range reference.
+ public ExcelTemplateComponentRange(string componentName, string sheetName, string reference)
+ {
+ ComponentName = componentName;
+ SheetName = sheetName;
+ Reference = reference;
+ }
+
+ ///
+ /// Gets the logical component name.
+ ///
+ public string ComponentName { get; }
+
+ ///
+ /// Gets the source sheet name.
+ ///
+ public string SheetName { get; }
+
+ ///
+ /// Gets the A1 range reference.
+ ///
+ public string Reference { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs
new file mode 100644
index 0000000..9512bbe
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs
@@ -0,0 +1,301 @@
+using ExcelReportLib.DSL;
+
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents the normalized conversion output contract used by ExcelTemplate emitters.
+///
+public sealed class ExcelTemplateOutputContract
+{
+ ///
+ /// Initializes a new instance of the output contract.
+ ///
+ /// The normalized component scopes.
+ /// The normalized sheet scopes.
+ /// The aggregated conversion issues.
+ public ExcelTemplateOutputContract(
+ IReadOnlyList? components = null,
+ IReadOnlyList? sheets = null,
+ IReadOnlyList? issues = null)
+ {
+ Components = components?.ToArray() ?? [];
+ Sheets = sheets?.ToArray() ?? [];
+ Issues = issues?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the normalized component scopes.
+ ///
+ public IReadOnlyList Components { get; }
+
+ ///
+ /// Gets the normalized sheet scopes.
+ ///
+ public IReadOnlyList Sheets { get; }
+
+ ///
+ /// Gets the aggregated conversion issues.
+ ///
+ public IReadOnlyList Issues { get; }
+}
+
+///
+/// Represents a normalized component scope for conversion output.
+///
+public sealed class ExcelTemplateOutputComponent
+{
+ ///
+ /// Initializes a new instance of the component scope.
+ ///
+ /// The logical component name.
+ /// The source component sheet name.
+ /// The resolved source range when available.
+ /// Whether the component range was successfully resolved.
+ /// The normalized output items.
+ public ExcelTemplateOutputComponent(
+ string name,
+ string sourceSheetName,
+ string? rangeReference,
+ bool isRangeResolved,
+ IReadOnlyList? items = null)
+ {
+ Name = name;
+ SourceSheetName = sourceSheetName;
+ RangeReference = rangeReference;
+ IsRangeResolved = isRangeResolved;
+ Items = items?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the logical component name.
+ ///
+ public string Name { get; }
+
+ ///
+ /// Gets the source component sheet name.
+ ///
+ public string SourceSheetName { get; }
+
+ ///
+ /// Gets the resolved source range when available.
+ ///
+ public string? RangeReference { get; }
+
+ ///
+ /// Gets a value indicating whether the component range was successfully resolved.
+ ///
+ public bool IsRangeResolved { get; }
+
+ ///
+ /// Gets the normalized output items.
+ ///
+ public IReadOnlyList Items { get; }
+}
+
+///
+/// Represents a normalized sheet scope for conversion output.
+///
+public sealed class ExcelTemplateOutputSheet
+{
+ ///
+ /// Initializes a new instance of the sheet scope.
+ ///
+ /// The sheet name.
+ /// The normalized output items.
+ public ExcelTemplateOutputSheet(
+ string name,
+ IReadOnlyList? items = null)
+ {
+ Name = name;
+ Items = items?.ToArray() ?? [];
+ }
+
+ ///
+ /// Gets the sheet name.
+ ///
+ public string Name { get; }
+
+ ///
+ /// Gets the normalized output items.
+ ///
+ public IReadOnlyList Items { get; }
+}
+
+///
+/// Represents a normalized output item within a component or sheet scope.
+///
+public abstract class ExcelTemplateOutputItem
+{
+ ///
+ /// Initializes a new instance of the output item.
+ ///
+ /// The A1 reference.
+ /// The 1-based row index.
+ /// The 1-based column index.
+ /// The workbook style index when present.
+ protected ExcelTemplateOutputItem(string reference, int row, int column, uint? styleIndex)
+ {
+ Reference = reference;
+ Row = row;
+ Column = column;
+ StyleIndex = styleIndex;
+ }
+
+ ///
+ /// Gets the A1 reference.
+ ///
+ public string Reference { get; }
+
+ ///
+ /// Gets the 1-based row index.
+ ///
+ public int Row { get; }
+
+ ///
+ /// Gets the 1-based column index.
+ ///
+ public int Column { get; }
+
+ ///
+ /// Gets the workbook style index when present.
+ ///
+ public uint? StyleIndex { get; }
+}
+
+///
+/// Represents a normalized value or formula cell.
+///
+public sealed class ExcelTemplateOutputCell : ExcelTemplateOutputItem
+{
+ ///
+ /// Initializes a new instance of the cell output item.
+ ///
+ /// The A1 reference.
+ /// The 1-based row index.
+ /// The 1-based column index.
+ /// The workbook style index when present.
+ /// The raw cell value.
+ /// The raw cell formula.
+ public ExcelTemplateOutputCell(
+ string reference,
+ int row,
+ int column,
+ uint? styleIndex,
+ string? value,
+ string? formula)
+ : base(reference, row, column, styleIndex)
+ {
+ Value = value;
+ Formula = formula;
+ }
+
+ ///
+ /// Gets the raw cell value.
+ ///
+ public string? Value { get; }
+
+ ///
+ /// Gets the raw cell formula.
+ ///
+ public string? Formula { get; }
+}
+
+///
+/// Represents a normalized use trigger.
+///
+public sealed class ExcelTemplateOutputUse : ExcelTemplateOutputItem
+{
+ ///
+ /// Initializes a new instance of the use output item.
+ ///
+ /// The A1 reference.
+ /// The 1-based row index.
+ /// The 1-based column index.
+ /// The workbook style index when present.
+ /// The referenced component name.
+ /// The normalized style overflow mode when explicitly known.
+ public ExcelTemplateOutputUse(
+ string reference,
+ int row,
+ int column,
+ uint? styleIndex,
+ string componentName,
+ string? styleOverflow)
+ : base(reference, row, column, styleIndex)
+ {
+ ComponentName = componentName;
+ StyleOverflow = styleOverflow;
+ }
+
+ ///
+ /// Gets the referenced component name.
+ ///
+ public string ComponentName { get; }
+
+ ///
+ /// Gets the normalized style overflow mode when explicitly known.
+ ///
+ public string? StyleOverflow { get; }
+}
+
+///
+/// Represents a normalized repeat-use trigger.
+///
+public sealed class ExcelTemplateOutputRepeatUse : ExcelTemplateOutputItem
+{
+ ///
+ /// Initializes a new instance of the repeat-use output item.
+ ///
+ /// The A1 reference.
+ /// The 1-based row index.
+ /// The 1-based column index.
+ /// The workbook style index when present.
+ /// The referenced component name.
+ /// The repeat source expression.
+ /// The repeat variable name.
+ /// The normalized repeat direction.
+ /// The normalized style overflow mode when explicitly known.
+ public ExcelTemplateOutputRepeatUse(
+ string reference,
+ int row,
+ int column,
+ uint? styleIndex,
+ string componentName,
+ string fromExpression,
+ string variableName,
+ string direction,
+ string? styleOverflow)
+ : base(reference, row, column, styleIndex)
+ {
+ ComponentName = componentName;
+ FromExpression = fromExpression;
+ VariableName = variableName;
+ Direction = direction;
+ StyleOverflow = styleOverflow;
+ }
+
+ ///
+ /// Gets the referenced component name.
+ ///
+ public string ComponentName { get; }
+
+ ///
+ /// Gets the repeat source expression.
+ ///
+ public string FromExpression { get; }
+
+ ///
+ /// Gets the repeat variable name.
+ ///
+ public string VariableName { get; }
+
+ ///
+ /// Gets the normalized repeat direction.
+ ///
+ public string Direction { get; }
+
+ ///
+ /// Gets the normalized style overflow mode when explicitly known.
+ ///
+ public string? StyleOverflow { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs
new file mode 100644
index 0000000..4c91303
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs
@@ -0,0 +1,46 @@
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents an extracted Excel template sheet.
+///
+public sealed class ExcelTemplateSheet
+{
+ ///
+ /// Initializes a new instance of the sheet model.
+ ///
+ /// The sheet name.
+ /// The extracted cells.
+ /// The extracted merged ranges.
+ /// Whether the sheet contains conditional formatting.
+ public ExcelTemplateSheet(
+ string name,
+ IReadOnlyList? cells = null,
+ IReadOnlyList? mergedRanges = null,
+ bool hasConditionalFormatting = false)
+ {
+ Name = name;
+ Cells = cells?.ToArray() ?? [];
+ MergedRanges = mergedRanges?.ToArray() ?? [];
+ HasConditionalFormatting = hasConditionalFormatting;
+ }
+
+ ///
+ /// Gets the sheet name.
+ ///
+ public string Name { get; }
+
+ ///
+ /// Gets the extracted cells.
+ ///
+ public IReadOnlyList Cells { get; }
+
+ ///
+ /// Gets the merged range references.
+ ///
+ public IReadOnlyList MergedRanges { get; }
+
+ ///
+ /// Gets a value indicating whether the sheet contains conditional formatting.
+ ///
+ public bool HasConditionalFormatting { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs
new file mode 100644
index 0000000..d640507
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs
@@ -0,0 +1,21 @@
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents extracted style metadata for a cell.
+///
+public sealed class ExcelTemplateStyle
+{
+ ///
+ /// Initializes a new instance of the style model.
+ ///
+ /// The workbook style index.
+ public ExcelTemplateStyle(uint index)
+ {
+ Index = index;
+ }
+
+ ///
+ /// Gets the workbook style index.
+ ///
+ public uint Index { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs
new file mode 100644
index 0000000..bd63ef9
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs
@@ -0,0 +1,32 @@
+namespace ExcelReportLib.ExcelTemplate.Model;
+
+///
+/// Represents an extracted Excel template workbook.
+///
+public sealed class ExcelTemplateWorkbook
+{
+ ///
+ /// Initializes a new instance of the workbook model.
+ ///
+ /// The extracted sheets.
+ /// The extracted defined names.
+ public ExcelTemplateWorkbook(
+ IReadOnlyList? sheets = null,
+ IReadOnlyDictionary? definedNames = null)
+ {
+ Sheets = sheets?.ToArray() ?? [];
+ DefinedNames = definedNames is null
+ ? new Dictionary(StringComparer.Ordinal)
+ : new Dictionary(definedNames, StringComparer.Ordinal);
+ }
+
+ ///
+ /// Gets the extracted sheets.
+ ///
+ public IReadOnlyList Sheets { get; }
+
+ ///
+ /// Gets the extracted workbook defined names.
+ ///
+ public IReadOnlyDictionary DefinedNames { get; }
+}
diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs
new file mode 100644
index 0000000..e91d9fd
--- /dev/null
+++ b/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs
@@ -0,0 +1,289 @@
+using ExcelReportLib.DSL;
+using System.Text;
+
+namespace ExcelReportLib.ExcelTemplate;
+
+///
+/// Parses ExcelTemplate use trigger strings into structured trigger metadata.
+///
+public sealed class UseTriggerParser
+{
+ ///
+ /// Parses a cell text value as a use trigger when applicable.
+ ///
+ /// The raw cell text.
+ /// The parse result.
+ public ExcelTemplateUseTriggerParseResult Parse(string? cellValue)
+ {
+ if (string.IsNullOrWhiteSpace(cellValue))
+ {
+ return ExcelTemplateUseTriggerParseResult.NotTrigger();
+ }
+
+ var trimmed = cellValue.Trim();
+ if (!trimmed.StartsWith("{{use:", StringComparison.Ordinal))
+ {
+ return ExcelTemplateUseTriggerParseResult.NotTrigger();
+ }
+
+ if (!trimmed.EndsWith("}}", StringComparison.Ordinal))
+ {
+ return ExcelTemplateUseTriggerParseResult.Invalid(" |