C#を使用したExcel変換のためのJSON配列のフラット化方法
C#を使用したExcel変換のためのJSON配列のフラット化方法
現代のAPIsやウェブサービスで働くとき、開発者はしばしば深く巣立つ根とオブジェクトを持つ複雑なJSON構造に直面します。これらの階層構造を平らなExcelテーブルに変換することは大きな課題です。このガイドは、効果的に巣立つJSON根をExcelに変換する方法を示しています Aspose.Cells for .NET。
挑戦:複雑なNested JSON構造
Web API からこの典型的な JSON 反応を検討する:
{
"company": "Acme Corp",
"departments": [
{
"name": "Engineering",
"employees": [
{
"id": 101,
"name": "John Smith",
"skills": ["C#", "ASP.NET", "Azure"]
},
{
"id": 102,
"name": "Jane Doe",
"skills": ["JavaScript", "React", "Node.js"]
}
]
},
{
"name": "Marketing",
"employees": [
{
"id": 201,
"name": "Michael Johnson",
"skills": ["Content Strategy", "SEO", "Analytics"]
}
]
}
]
}
この階層データをフラット Excel テーブルに変換すると、いくつかの課題が生じます。
- 複数のネックレスを処理する方法(部門、従業員、スキル)
- 親と子の物件との関係を維持する方法
- 読みやすいスプレッドシート構造を作成する方法
ステップ・ステップソリューション
ステップ1: Aspose.Cells をインストール
まず、 .NET のための Aspose.Cells をインストールします。
dotnet add package Aspose.Cells
ステップ2: JsonLayoutOptions を設定する
適切に設定された JsonLayoutOptions を作成してラリーを処理する:
using Aspose.Cells;
using Aspose.Cells.Utility;
// Create JsonLayoutOptions with array handling
JsonLayoutOptions options = new JsonLayoutOptions();
options.ArrayAsTable = true; // Crucial for proper flattening
options.ConvertNumericOrDate = true;
options.IgnoreNull = true;
ステップ3:複雑なJSONデータの充電
あなたの複雑なNested JSON データをアップロードする:
// Sample JSON with nested arrays
string jsonData = File.ReadAllText("complex_data.json");
// Initialize workbook and worksheet
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
ステップ4:高度なフラットを設定する
先進的な巣構造では、カスタマイズされたフラッティングソリューションを実施します:
// Define starting cell position
int startRow = 0;
int startColumn = 0;
// Import the JSON data with our configured options
JsonUtility.ImportData(jsonData, worksheet.Cells, startRow, startColumn, options);
ステップ5:マルチレベルのネスティードアレイを処理する
複雑な複数のレベルのラリーには、追加の処理が必要です:
// Create a second worksheet for detailed employee data
Worksheet employeeSheet = workbook.Worksheets.Add("Employees");
int empRow = 0;
// Add headers for the employee sheet
string[] headers = { "Department", "Employee ID", "Employee Name", "Skills" };
for (int i = 0; i < headers.Length; i++)
{
employeeSheet.Cells[empRow, i].PutValue(headers[i]);
}
empRow++;
// Parse JSON to extract and flatten employee data
// Note: This would require a JSON parsing library like Newtonsoft.Json
// JObject root = JObject.Parse(jsonData);
// foreach (var dept in root["departments"])
// {
// string deptName = dept["name"].ToString();
// foreach (var emp in dept["employees"])
// {
// employeeSheet.Cells[empRow, 0].PutValue(deptName);
// employeeSheet.Cells[empRow, 1].PutValue((int)emp["id"]);
// employeeSheet.Cells[empRow, 2].PutValue(emp["name"].ToString());
// employeeSheet.Cells[empRow, 3].PutValue(string.Join(", ", emp["skills"].ToObject<string[]>()));
// empRow++;
// }
// }
ステップ6:プロフェッショナルフォーマットを適用
適切なフォーマットで読みやすさを向上させる:
// Format both worksheets as tables with headers
worksheet.ListObjects.Add(0, 0, worksheet.Cells.LastCell.Row, worksheet.Cells.LastCell.Column, true);
employeeSheet.ListObjects.Add(0, 0, empRow - 1, 3, true);
// Auto-fit columns for better readability
worksheet.AutoFitColumns();
employeeSheet.AutoFitColumns();
ステップ7:結果を保存する
フラットデータを含むワークブックを輸出する:
// Save as Excel file
workbook.Save("flattened_data.xlsx");
ASPOSE.CELL を使用したシンプルなソリューション
多くのシナリオでは、Aspose.Cellsは、その内蔵JSON処理を使用して、よりシンプルなアプローチを提供します。
// Initialize workbook
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
// Configure JSON import options
JsonLayoutOptions options = new JsonLayoutOptions
{
ArrayAsTable = true,
ConvertNumericOrDate = true,
IgnoreNull = true,
TitleStyle = new CellsFactory().CreateStyle(),
NestedArrayAsTable = true // Important for nested arrays
};
// Set title style for better readability
options.TitleStyle.Font.IsBold = true;
// Import JSON
JsonUtility.ImportData(jsonData, sheet.Cells, 0, 0, options);
// Save result
workbook.Save("flattened_output.xlsx");
キー・インスピレーションとベスト・プラクティス
- Use ArrayAsTable = true - これは、ラリーの適切な表現に不可欠です。
- 複雑な階層データのための複数のワークシートを作成することを検討する
- フォーマットを適用する 結果をより読みやすくするために
- NestedArrayAsTable を使用する = 真実 より良い処理のために利用可能な場合
- **非常に複雑な構造については、輸入前にJSONを事前に処理することを検討してください。
一般的な問題と解決策
問題 | 解決策 |
---|---|
シングル細胞として現れます。 | 可能 ArrayAsTable そして、 NestedArrayAsTable オプション |
データ関係が失われた。 | 関係列で複数のテーブル/シートを作成する |
コラム名が間違っています。 | 使用する The DateTimeGroupSeparator 名称をカスタマイズする方法 |
大ファイルによるメモリ問題 | JSONをチューンで処理するか、ストリーミングアプローチを使用する |