Cách làm phẳng mảng JSON để chuyển đổi sang Excel bằng C#
Khi làm việc với các APIs hiện đại và các dịch vụ web, các nhà phát triển thường gặp các cấu trúc JSON phức tạp với các cấu trúc và đối tượng sâu thẳm. Chuyển đổi các cấu trúc hiệp định này sang các bảng Excel phẳng là một thách thức đáng kể. Hướng dẫn này cho thấy làm thế nào để chuyển đổi các cấu trúc JSON sâu thẳm thành Excel bằng cách sử dụng Aspose.Cells cho .NET.
Thách thức: Các cấu trúc JSON Nested phức tạp
Hãy xem xét phản ứng JSON điển hình này từ một 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"]
}
]
}
]
}
Chuyển đổi dữ liệu sơ bộ này sang một bảng Excel phẳng tạo ra một số thách thức:
- Làm thế nào để xử lý nhiều vết sẹo (các bộ phận, nhân viên, kỹ năng)
- Làm thế nào để duy trì mối quan hệ giữa cha mẹ và trẻ em
- Làm thế nào để tạo ra một cấu trúc spreadsheet dễ đọc
Giải pháp Step-by-Step
Bước 1: Cài đặt Aspose.Cells
Đầu tiên, cài đặt Aspose.Cells cho .NET:
dotnet add package Aspose.Cells
Bước 2: Tạo JsonLayoutOptions
Tạo JsonLayoutOptions được cấu hình đúng cách để xử lý rào cản:
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;
Bước 3: Load Complex JSON Data
Tải về dữ liệu JSON phức tạp của bạn:
// 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];
Bước 4: Thiết lập Advanced Flattening
Đối với các cấu trúc mọc tiên tiến, thực hiện một giải pháp mọc tùy chỉnh:
// 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);
Bước 5: Quản lý nhiều cấp Nested Arrays
Đối với các mảng đa cấp phức tạp, chúng tôi cần xử lý bổ sung:
// 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++;
// }
// }
Bước 6: Sử dụng Formatting chuyên nghiệp
Tăng khả năng đọc bằng định dạng thích hợp:
// 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();
Bước 7: Tiết kiệm kết quả
Xuất khẩu sổ làm việc với dữ liệu nhấp nháy:
// Save as Excel file
workbook.Save("flattened_data.xlsx");
Một giải pháp đơn giản sử dụng Aspose.Cells
Đối với nhiều kịch bản, Aspose.Cells cung cấp một cách tiếp cận đơn giản hơn bằng cách sử dụng xử lý JSON tích hợp:
// 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");
Những hiểu biết và thực hành tốt nhất
- Use ArrayAsTable = true - Điều này là cần thiết cho sự đại diện thích hợp của array
- Hãy xem xét việc tạo nhiều bảng tính cho dữ liệu hiến pháp phức tạp
- Hãy áp dụng định dạng để làm cho kết quả dễ đọc hơn
- Use NestedArrayAsTable = true khi có sẵn để xử lý tốt hơn các cấu trúc Nested
- Đối với các cấu trúc cực kỳ phức tạp, hãy xem xét việc xử lý JSON trước khi nhập khẩu
Vấn đề Thường Gặp và Giải Pháp
vấn đề | Giải pháp |
---|---|
Các vết sẹo xuất hiện như các tế bào duy nhất | Khả năng ArrayAsTable và NestedArrayAsTable Lựa chọn |
Mối quan hệ dữ liệu bị mất | Tạo nhiều bảng / bảng với các cột mối quan hệ |
Tên cột không chính xác | Sử dụng The DateTimeGroupSeparator Tùy chọn tùy chỉnh tên |
Vấn đề bộ nhớ với các tập tin lớn | Xử lý JSON trong các mảnh hoặc sử dụng cách tiếp cận streaming |