Quando si lavora con le moderne API e i servizi web, gli sviluppatori spesso incontrano strutture JSON complesse con aria e oggetti profondamente nestati. Convertire questi dati ierarchici in tabelle piatte di Excel presenta una sfida significativa. Questo manuale dimostra come convertire efficacemente arie Nestate di J SON in Excel utilizzando Aspose.Cell per .NET.
Introduzione
Quando si lavora con le moderne API e i servizi web, gli sviluppatori spesso incontrano strutture JSON complesse con aria e oggetti profondamente nestati. Convertire questi dati ierarchici in tabelle piatte di Excel presenta una sfida significativa. Questo manuale dimostra come convertire efficacemente arie Nestate di J SON in Excel utilizzando Aspose.Cell per .NET.
La sfida: strutture JSON Nested complesse
Considerare questa risposta JSON tipica da un web API:
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 correttamente configurato JsonLayoutOptions
Per gestire i rifiuti:
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 |
More in this category
- Assicurare i documenti sensibili di Excel con Aspose.Cells LowCode Spreadsheet Locker
- Conversione automatica di Excel in PDF in .NET
- Convertire efficacemente i file Excel in e da JSON con Aspose.Cells
- Convertire Excel in immagine con un background trasparente in C#
- Convertire Excel in Immagine di Thumbnail in C#