这个简短的教程解释了如何使用 C#** 将 JSON 文件转换为 Excel,方法是从任何来源读取 JSON 数据,然后在定义导入数据的格式后将其保存为 Excel 文件,例如 XLSX。将加载一个空的或现有的工作簿,并将 JSON 数据导入所选工作表中用户定义的起始单元格。在使用 C#** 将 **JSON 转换为 Excel 的过程中,您将可以完全控制字体设置、网格显示、文本对齐、页面设置和各种其他参数。
使用 C# 将 JSON 文件转换为 Excel 的步骤
- 从 NuGet 包管理器添加对 Aspose.Cells 库的引用以将 JSON 文件转换为 Excel
- 通过设置不同的属性(如对齐方式、字体颜色和粗体标志)为 JSON 数据标题创建样式
- 使用上述样式和其他标志初始化 JsonLayoutOptions 类对象
- 创建一个空的 Workbook 并获取对目标工作表的引用
- 将整个 JSON 内容读入字符串变量
- 调用 JsonUtility 类的 ImportData 函数将 JSON 字符串转换为 Excel
- 保存包含导入 JSON 数据的输出 Excel 文件
这里我们首先初始化输出 Excel 文件中标题所需的可选格式参数。在下一步中,初始化工作簿并获得对目标工作表的引用。最后,源 JSON 数据被加载到一个字符串变量中,并在 ImportData 函数中用作参数以及其他所需信息。 将 JSON 导出到 Excel C# 示例代码如下所示。
在 C# 中将 JSON 转换为 Excel 的代码
using Aspose.Cells; | |
using System.IO; | |
using Aspose.Cells.Utility; | |
namespace ConvertCsvToPdfUsingCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Instantiate the license at the beginning of the program to avoid trial version restrictions | |
License JsonToExcelLicense = new License(); | |
JsonToExcelLicense.SetLicense("Aspose.Cells.lic"); | |
// Create a style to format the json fields title in the output workbook | |
CellsFactory factory = new CellsFactory(); | |
Style jsonTitleStyle = factory.CreateStyle(); | |
jsonTitleStyle.HorizontalAlignment = TextAlignmentType.Center; | |
jsonTitleStyle.Font.Color = System.Drawing.Color.BlueViolet; | |
jsonTitleStyle.Font.IsBold = true; | |
// Declare and define the layout of the data imported from JSON to Excel | |
JsonLayoutOptions jsonLayoutOptions = new JsonLayoutOptions(); | |
jsonLayoutOptions.TitleStyle = jsonTitleStyle; | |
jsonLayoutOptions.ArrayAsTable = true; | |
// Initialize an empty workbook to import JSON data | |
Workbook emptyWbForJsonData = new Workbook(); | |
// Get reference to the worksheet where data is to be imported | |
Worksheet targetWorksheet = emptyWbForJsonData.Worksheets[0]; | |
// Read the Json file into a string variable that will be used to import date | |
string inputJsonString = File.ReadAllText("SampleJsonData.json"); | |
// Call the ImportData function to import JSON data into the worksheet | |
JsonUtility.ImportData(inputJsonString, targetWorksheet.Cells, 3, 5, jsonLayoutOptions); | |
// Save Excel file | |
emptyWbForJsonData.Save("SampleJsonToXlsx.xlsx"); | |
} | |
} | |
} |
此代码使用 CellsFactory 通过定义稍后在 JsonLayoutOptions 对象中使用的水平对齐和字体设置来为输出 JSON 数据标题创建样式。 JsonUtility.ImportData() 函数需要源 JSON 字符串、对目标工作表的 Cells 集合的引用、要导入数据的第一行和第一列以及在程序开始时设置的布局选项。
这个简短的教程指导我们如何使用 C# 将 JSON 转换为 Excel。但是,如果您想了解如何将 JSON 转换为 CSV,请参阅 如何在 C# 中将 JSON 转换为 CSV 上的文章。