Cómo aplanar un array JSON para la conversión a Excel con C#
Al trabajar con las APIs modernas y los servicios web, los desarrolladores a menudo encuentran estructuras JSON complejas con aráreas y objetos profundamente nested. Convertir estas estructuras jerárquicas en tablas de Excel plana presenta un reto significativo. Esta guía demuestra cómo convertir de manera eficaz aráreas JSON nested a Excel utilizando Aspose.Cells para .NET.
El desafío: las estructuras complejas de JSON
Considere esta respuesta JSON típica de 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 estos datos jerárquicos en una tabla plana de Excel crea varios retos:
- Cómo gestionar múltiples arándanos (departamentos, empleados, habilidades)
- Cómo mantener las relaciones entre padres y hijos
- Cómo crear una estructura de spreadsheet ligable
Solución paso a paso
Paso 1: Instalar Aspose.Cells
En primer lugar, instale Aspose.Cells para .NET:
dotnet add package Aspose.Cells
Paso 2: Instalar JsonLayoutOptions
Crear JsonLayoutOptions correctamente configurados para gestionar los rasgos:
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;
Paso 3: Cargar los datos complejos JSON
Cargue sus datos complejos 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];
Paso 4: Configure Flattening Avanzado
Para las estructuras de nido avanzadas, implementar una solución de flexión personalizada:
// 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);
Paso 5: Tratar las arrastradas de multi-nivel
Para el complejo arras multi-nivel, necesitamos procesamiento adicional:
// 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++;
// }
// }
Paso 6: Aplique la formatación profesional
Mejora la lectura con el formato adecuado:
// 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();
Paso 7: Salva el resultado
Exporta el libro de trabajo con datos flattados:
// Save as Excel file
workbook.Save("flattened_data.xlsx");
Una solución simplificada con Aspose.Cells
Para muchos escenarios, Aspose.Cells proporciona un enfoque más sencillo utilizando su manejo JSON integrado:
// 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");
Principios y mejores prácticas
- Use ArrayAsTable = verdad - Esto es esencial para la adecuada representación de los array
- Considerar la creación de múltiples hojas de trabajo para los datos jerárquicos complejos
- Aplicar el formato para hacer que la salida sea más ligable
- Use NestedArrayAsTable = verdadero cuando esté disponible para un mejor manejo de estructuras nested
- Para estructuras extremadamente complejas, considere pre-procesar el JSON antes de importar
Problemas Comunes y Soluciones
Problemas | Solución |
---|---|
Los arándanos se muestran como células únicas | Permite ArrayAsTable y NestedArrayAsTable Opciones |
Se perdieron las relaciones de datos | Crear múltiples tablas/cortes con columnas de relación |
Los nombres de las columnas son incorrectos | Utilice el DateTimeGroupSeparator Opción para personalizar el nombre |
Problemas de memoria con grandes archivos | Procesar el JSON en fragmentos o utilizar enfoques de streaming |