Come appiattire un array JSON per la conversione in Excel con C#
Quando si lavora con le moderne API e i servizi web, gli sviluppatori spesso incontrano strutture JSON complesse con strutture e oggetti profondamente nestati. Conversione di queste strutture gerarchiche in tabelle Excel piatte presenta una sfida significativa. Questa guida dimostra come convertire efficacemente strutture JSON nestate in Excel utilizzando Aspose.Cell per .NET.
La sfida: strutture JSON Nested complesse
Considerare questa risposta JSON tipica da un web API:
{
"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"]
}
]
}
]
}
Convertire questi dati ierarchici in una tabella piatta di Excel crea diversi sfidi:
- Come gestire molteplici radiazioni (departamenti, dipendenti, abilità)
- Come mantenere le relazioni tra genitori e bambini
- Come creare una struttura di spreadsheet leggibile
Soluzione passo dopo passo
Passo 1: Installare Aspose.Cells
In primo luogo, installare Aspose.Cells per .NET:
dotnet add package Aspose.Cells
Passo 2: Impostare JsonLayoutOptions
Creare JsonLayoutOptions correttamente configurati per gestire i rami:
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;
Passo 3: Caricare i dati JSON complessi
Carica i tuoi dati JSON complessi:
// 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];
Passo 4: Configurare Flattening avanzato
Per le strutture nestate avanzate, implementare una soluzione di flattamento personalizzata:
// 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);
Passo 5: Gestire il multi-level Nested Arrays
Per il complesso multi-level array, abbiamo bisogno di ulteriore elaborazione:
// 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++;
// }
// }
Passo 6: Applicare la formattazione professionale
Migliora la lettura con il corretto formattamento:
// 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();
Passo 7: Salva il risultato
Esportare il libro di lavoro con i dati flattati:
// Save as Excel file
workbook.Save("flattened_data.xlsx");
Una soluzione semplificata utilizzando Aspose.Cells
Per molti scenari, Aspose.Cells fornisce un approccio più semplice utilizzando la sua gestione JSON integrata:
// 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");
Le idee chiave e le migliori pratiche
- Use ArrayAsTable = vero - Questo è essenziale per la corretta rappresentazione degli array
- Considerare la creazione di più fogli di lavoro per i dati ierarchici complessi
- Applicare la formattazione per rendere la produzione più leggibile
- Uso NestedArrayAsTable = vero quando disponibile per una migliore gestione delle strutture nestate
- Per strutture estremamente complesse, considerare il prelievo del JSON prima dell’importazione
Problemi Comuni e Soluzioni
Il problema | La soluzione |
---|---|
I rami nascosti appaiono come singole cellule | Permette ArrayAsTable e NestedArrayAsTable Opzioni |
I rapporti di dati sono persi | Creare più tabelle / schede con colonne di relazione |
I nomi delle colonne sono errati | Utilizzare il DateTimeGroupSeparator Opzione di personalizzare il nome |
Problemi di memoria con grandi file | Processare il JSON in pezzi o utilizzare approcci di streaming |