C#로 Excel 변환을 위한 JSON 배열 평탄화 방법
C#로 Excel 변환을 위한 JSON 배열 평탄화 방법
현대 APIs 및 웹 서비스와 함께 일할 때 개발자는 종종 깊이 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게 둥글게.
도전 : 복잡한 Nested JSON 구조
웹 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 설치
먼저 .NET을 위한 Aspose.Cells를 설치하십시오.
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 사용 = 진실 더 나은 둥근 구조 관리에 사용할 수 있는 경우
- 매우 복잡한 구조를 위해, 수입하기 전에 JSON을 사전 처리하는 것을 고려하십시오.
일반적인 문제 및 해결책
문제 | 해결책 |
---|---|
둥근 뿌리는 단일 세포로 나타납니다. | 할 수 있는 ArrayAsTable 그리고 NestedArrayAsTable 옵션 |
데이터 관계가 잃어버린다 | 관계 열을 사용하여 여러 테이블/시트 만들기 |
열 이름이 잘못되었습니다. | 사용하시기 바랍니다 DateTimeGroupSeparator 명칭을 사용자 정의 할 수있는 옵션 |
메모리 문제 큰 파일 | JSON을 조각으로 처리하거나 스트리밍 접근 방식을 사용합니다. |