如何使用C#将JSON数组扁平化以进行Excel转换

如何使用C#将JSON数组扁平化以进行Excel转换

在与现代API和网页服务工作时,开发人员经常会遇到复杂的JSON结构与深沉的序列和对象。 将这些序列结构转化为平板的Excel表是一个显著的挑战. 本指南展示了如何有效地使用 Aspose.Cells for .NET 将序列转化为Excel。

挑战:复杂的JSON结构

考虑一下从 Web API 的典型 JSON 响应:

{
  "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"]
        }
      ]
    }
  ]
}

将这些序列数据转换为平板 Excel 表,创造了几个挑战:

  • 如何处理多种粘土(部门、员工、技能)
  • 如何保持父母与儿童物品之间的关系
  • 如何创建可读的布局结构

步骤解决方案

步骤1:安装 Aspose.Cells

首先,安装 Aspose.Cells for .NET:

dotnet add package Aspose.Cells

步骤2:设置 JsonLayoutOptions

创建正确配置的 JsonLayoutOptions 以处理草坪:

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;

步骤3:充电JSON数据

加载您的复杂的 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];

步骤4:设置先进的平板

对于先进的粘贴结构,实施自定义的粘贴解决方案:

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

步骤5:处理多层滑板

对于复杂的多级轴承,我们需要额外的处理:

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

步骤6:应用专业格式化

通过正确的格式化提高阅读能力:

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

步骤7:保存结果

输出工作簿与浮动数据:

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

使用 Aspose.Cells 的简化解决方案

在许多情况下,Aspose.Cells提供了一个更简单的方法,使用其内置的JSON处理:

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

关键洞察和最佳实践

  • Use ArrayAsTable = true - 这对于正确的描述是必不可少的。
  • 考虑为复杂的序列数据创建多个工作表
  • 应用格式化 使输出更可读
  • 使用NestedArrayAsTable = true 当可用于更好的处理Nested结构时
  • **对于非常复杂的结构,请考虑在进口前提前处理JSON。

常见问题及解决方案

问题解决方案
种植的子看起来像单细胞允许 ArrayAsTableNestedArrayAsTable 选项
数据关系失去了使用关系列创建多个表 / 列
列名称不正确使用 The DateTimeGroupSeparator 可自定义名称
記憶體問題與大檔案将 JSON 处理成碎片或使用流通方法
 中文