Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert .json file to excel in c#

Tags:

c#-4.0

I want to convert .json file to excel . iam not able to find the solution anywhere for these issue using c# language . Could any one help me out with these along with exact solution.

like image 345
user3628181 Avatar asked Sep 07 '14 08:09

user3628181


People also ask

How do I convert a JSON to a spreadsheet?

To start parsing a JSON file, open Microsoft Excel on your computer and start a new spreadsheet. On the spreadsheet window, in Excel's ribbon at the top, click the “Data” tab. On the “Data” tab, from the “Get & Transform Data” section, select Get Data > From File > From JSON.

How do I convert multiple JSON files to Excel?

Select all the columns that contain data values. Select Home, the arrow next to Remove Columns, and then select Remove Other Columns. Select Home > Close & Load. Power Query automatically creates a query to consolidate the data from each file into a worksheet.


2 Answers

It depends on the data and what you want to achieve on the Excel side. I would tackle this with Json.NET and output to a CSV file, which may be opened in Excel.

Consider the following JSON... a simple array

[{
    "foo": "bar"
}]

With Json.NET we can do the following to get it into C#

var jsonData = "[{ \"foo\": \"bar\" }]";

var jsonDefinition = new object[]
{
    new {foo = ""}
};

var result = JsonConvert.DeserializeAnonymousType(jsonData, jsonDefinition);

We can then loop through the structure, outputting to a CSV file.

var sb = new StringBuilder();
foreach (dynamic o in result)
{
    sb.AppendLine(o.foo);
}
File.WriteAllText(@"c:\code\test.csv", sb.ToString());
like image 40
Krisc Avatar answered Oct 19 '22 23:10

Krisc


Here is another partial solution, that doesn't require making a json definition, as long as the json is in a table format.

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

From here, you can use any of the numerous datatable -> excel solutions available on the internet.

Many are posted here: How to export DataTable to Excel

like image 190
Kyle Avatar answered Oct 19 '22 22:10

Kyle