How to convert JSON document to CSV format document?
14 Jul 20253 minutes to read
The following code illustrates how to convert JSON document to CSV format document.
//Load JSON file
string jsonPath = Path.GetFullPath("Data/Input.json");
string jsonData = File.ReadAllText(jsonPath);
//Deserialize to DataTable
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonData);
//Initialize ExcelEngine
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
//Import DataTable to worksheet
sheet.ImportDataTable(dataTable, true, 1, 1);
//Saving the workbook as CSV
FileStream outputStream = new FileStream(Path.GetFullPath("Output/Sample.csv"), FileMode.Create, FileAccess.ReadWrite);
workbook.SaveAs(outputStream, ",");
//Dispose streams
outputStream.Dispose();
}
//Load JSON file
string jsonPath = Path.GetFullPath("Input.json");
string jsonData = File.ReadAllText(jsonPath);
//Deserialize to DataTable
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonData);
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
//Import DataTable to worksheet
sheet.ImportDataTable(dataTable, true, 1, 1);
//Saving the workbook as CSV
workbook.SaveAs("Output.csv",",");
}
'Load JSON file
Dim jsonPath As String = Path.GetFullPath("Data/Input.json")
Dim jsonData As String = File.ReadAllText(jsonPath)
'Deserialize to DataTable
Dim dataTable As DataTable = JsonConvert.DeserializeObject(Of DataTable)(jsonData)
'Initialize ExcelEngine
Using excelEngine As ExcelEngine = New ExcelEngine()
Dim application As IApplication = excelEngine.Excel
application.DefaultVersion = ExcelVersion.Xlsx
Dim workbook As IWorkbook = application.Workbooks.Create(1)
Dim sheet As IWorksheet = workbook.Worksheets(0)
'Import DataTable to worksheet
sheet.ImportDataTable(dataTable, True, 1, 1)
'Saving the workbook as CSV
workbook.SaveAs("Output.csv", ",")
End Using
A complete working example to convert JSON document to CSV format document using C# is present on this GitHub page.