Com fer Flat JSON Array per a la conversió d'Excel amb C#
Quan treballen amb les APIs modernes i els serveis web, els desenvolupadors sovint troben complexos JSON Convertir aquestes estructures jeràrquics en taules de Excel plana presenta un repte important. Aquesta guia demostra com convertir eficaçment les arrels de JSON a Excel utilitzant Aspose.Cells per .NET.
El repte: estructures complexes Nested JSON
Considera aquesta resposta JSON típica d’una API web:
{
"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"]
}
]
}
]
}
Convertir aquests dades jeràrquics en una taula plana d’Excel crea diversos reptes:
- Com gestionar múltiples arrels nestades (departaments, empleats, habilitats)
- Com mantenir les relacions entre pares i infants
- Com crear una estructura de fletxa lliure
Solució de pas a pas
Pas 1: Instal·lar Aspose.Cells
Primer, instal·la Aspose.Cells per a .NET:
dotnet add package Aspose.Cells
Pas 2: Instal·lació de JsonLayoutOptions
Crear opcions JsonLayout correctament configurades per gestionar les arrels:
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;
Pas 3: Carregar les dades complexes JSON
Carrega les teves dades complexes de 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];
Pas 4: Configuració avançada Flattening
Per a estructures nestades avançades, implementar una solució de flotatge personalitzada:
// 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);
Pas 5: Gestió d’arres Nested de múltiples nivells
Per a complexos arrels multi-nivells, necessitem un processament addicional:
// 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++;
// }
// }
Pas 6: Aplica la formatació professional
Millorar la lectura amb el correcte format:
// 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();
Pas 7: Salvar el resultat
Exportar el llibre de treball amb dades flatulents:
// Save as Excel file
workbook.Save("flattened_data.xlsx");
Una solució simplificada amb Aspose.Cells
Per a molts escenaris, Aspose.Cells proporciona un enfocament més senzill utilitzant el seu maneig JSON integrat:
// 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");
Consideracions clau i millors pràctiques
- Use ArrayAsTable = veritable - Això és essencial per a la correcta representació dels arrels
- Considerar la creació de múltiples tauletes per a dades jeràrquics complexes
- Aplicar el format per fer que la producció sigui més llegible
- Use NestedArrayAsTable = veritable quan està disponible per a una millor gestió de les estructures nestades
- Per a estructures extremadament complexes, considereu pre-processar el JSON abans d’importar
Problemes comuns i solucions
qüestió | Solució |
---|---|
Les arrels Nested apareixen com a cèl·lules soles | Enable ArrayAsTable i NestedArrayAsTable Opcions |
Les relacions de dades estan perdudes | Creació de taules / taules múltiples amb columnes de relació |
Els noms de columnes són incorrectes | Utilitza el DateTimeGroupSeparator Opció de personalitzar el nom |
Problemes de memòria amb grans fitxers | Processar el JSON en trossos o utilitzar enfocaments de streaming |