Cum de a Flatte JSON Array pentru Excel Conversion cu C#

Cum de a Flatte JSON Array pentru Excel Conversion cu C#

Atunci când lucrează cu API-urile moderne și serviciile web, dezvoltatorii întâlnesc adesea structuri complexe JSON cu raze și obiecte adânc nestate. Conversia acestor structura ierarhice în tabele Excel plat prezintă o provocare semnificativă. Acest ghid demonstrează cum să se convertească în mod eficient razesele NSON în Excel folosind Aspose.Cells pentru .NET.

Cuvânt cheie: structuri JSON complexe

Gândiți-vă la această răspuns tipic JSON dintr-o 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"]
        }
      ]
    }
  ]
}

Conversia acestor date ierarhice într-un tabel Excel plat creează mai multe provocări:

  • Cum să se ocupe de mai multe raze nestate (departamente, angajați, abilități)
  • Cum să menținem relațiile dintre părinte și copil
  • Cum să creați o structură ușor de citit

Soluție pas cu pas

Pasul 1: Instalați Aspose.Cells

În primul rând, instalați Aspose.Cells pentru .NET:

dotnet add package Aspose.Cells

Pasul 2: Setarea JsonLayoutOptions

Creați JsonLayoutOptions configurate în mod corespunzător pentru a gestiona raze:

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;

Pasul 3: încărcați Complexul de date JSON

Încărcați datele JSON complexe:

// 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];

Pasul 4: Configurați Flattening avansat

Pentru structurile avansate nestate, implementați o soluție de flatulență personalizată:

// 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);

Pasul 5: Tratarea armelor Nested de mai multe niveluri

Pentru raze complexe de mai multe niveluri, avem nevoie de prelucrare suplimentară:

// 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++;
//     }
// }

Pasul 6: Aplicați formarea profesională

Îmbunătățiți citibilitatea cu formatarea corectă:

// 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();

Pasul 7: Salvați rezultatul

Exportați cartea de lucru cu date flatulente:

// Save as Excel file
workbook.Save("flattened_data.xlsx");

O soluție simplificată folosind Aspose.Cells

Pentru multe scenarii, Aspose.Cells oferă o abordare mai simplă folosind manipularea JSON încorporată:

// 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");

Principalele idei și cele mai bune practici

  • Use ArrayAsTable = true - Acest lucru este esențial pentru reprezentarea corespunzătoare a razelor
  • Consideră crearea mai multor panouri de lucru pentru date ierarhice complexe
  • Aplicați formatul pentru a face rezultatul mai citit
  • Use NestedArrayAsTable = adevărat atunci când este disponibil pentru o mai bună gestionare a structurilor nestate
  • Pentru structuri extrem de complexe, luați în considerare prelucrarea JSON înainte de import

Probleme și soluții comune

problemăSoluţie
Ursele nested apar ca celule uniceEnable ArrayAsTable and NestedArrayAsTable options
Relațiile de date sunt pierduteCreați mai multe tabele / tabele cu coloane de relație
Numele coloanei este incorectUse the DateTimeGroupSeparator option to customize naming
Probleme de memorie cu fișierele mariProcesarea JSON-ului în bucăți sau utilizarea abordărilor de streaming
 Română