40

Does anyone have any sample Java code to convert a JSON document to XLS/CSV file? I have tried to search on Google but to no avail.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
BachLover2342
  • 417
  • 1
  • 4
  • 3

3 Answers3

45

You could only convert a JSON array into a CSV file.

Lets say, you have a JSON like the following :

{"infile": [{"field1": 11,"field2": 12,"field3": 13},
            {"field1": 21,"field2": 22,"field3": 23},
            {"field1": 31,"field2": 32,"field3": 33}]}

Lets see the code for converting it to csv :

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSON2CSV {
    public static void main(String myHelpers[]){
        String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";

        JSONObject output;
        try {
            output = new JSONObject(jsonString);


            JSONArray docs = output.getJSONArray("infile");

            File file=new File("/tmp2/fromJSON.csv");
            String csv = CDL.toString(docs);
            FileUtils.writeStringToFile(file, csv);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
    }

}

Now you got the CSV generated from JSON.

It should look like this:

field1,field2,field3
11,22,33
21,22,23
31,32,33

The maven dependency was like,

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Update Dec 13, 2019:

Updating the answer, since now we can support complex JSON Arrays as well.

import java.nio.file.Files;
import java.nio.file.Paths;

import com.github.opendevl.JFlat;

public class FlattenJson {

    public static void main(String[] args) throws Exception {
        String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));

        JFlat flatMe = new JFlat(str);

        //get the 2D representation of JSON document
        flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();

        //write the 2D representation in csv format
        flatMe.write2csv("path_to_output.csv");
    }

}

dependency and docs details are in link

Sridhar
  • 1,518
  • 14
  • 27
  • Thank you for this code but I'm new to Java and have problem to make it work. The `jsonout` and `response` variables are not defined. Any idea? Thanks again! – hhh Apr 18 '15 at 09:58
  • FileUtils.writeStringToFile(file, csv); is deprecated – Swap L Oct 06 '16 at 10:27
  • is there another way than using org.json.CDL? I seem to not be able to import that class into my Android project – keinabel Nov 21 '16 at 13:23
  • 3
    @SwapL You can use the 3 parameter method of the same. `FileUtils.writeStringToFile(file, csv, null);` where the 3rd parameter is encoding & null is for platform default. – Sridhar Dec 05 '16 at 08:04
  • 1
    @keinabel I'm not sure I guess there is a CDL library in apache. you can check that too. But, not sure whether that will work. Else, you have to write a loop to iterate the json array. which is a pain :( So, let me know which one worked for you. Good luck. – Sridhar Dec 05 '16 at 08:11
  • @Sridhar hi sir,this code is not working for excel format,please tell me what i have to change how can achieve... – Gowthaman M Aug 10 '17 at 07:01
  • 2
    @GowthamanM You can use [apache-poi](https://poi.apache.org/) library to write to excel files. But, you have to iterate the JsonArray `docs` to write every individual cell. – Sridhar Aug 10 '17 at 16:11
  • @Sridhar Thank you for your suggestion,I stored csv format as your code, and by Intent i am calling excel file its working for me perfectly thax lot bro. – Gowthaman M Aug 10 '17 at 18:46
  • @GowthamanM Happy to help. – Sridhar Aug 11 '17 at 08:51
  • @Sridhar Hi sir,I have one more doubt how to show `progressDialog` how much percentage downloaded,please guide me... – Gowthaman M Aug 16 '17 at 05:32
  • @GowthamanM You can get total file length from headers and total downloaded byte size from your (still downloading) local file. So, `(downloaded_size / total_size) * 100` will give % downloaded [reference_link](https://stackoverflow.com/questions/11503791/progress-bar-completed-download-display-in-android) – Sridhar Aug 16 '17 at 11:04
  • @Sridhar Thank you sir,Is there any possible we can make First row of excel as black color with bold letters. – Gowthaman M Aug 18 '17 at 05:26
  • @GowthamanM I hope [this](https://stackoverflow.com/questions/12286662/how-to-apply-bold-text-style-for-an-entire-row-using-apache-poi) helps you. Please upvote answers if it helps you. – Sridhar Aug 18 '17 at 10:45
  • Hi sir,,Above code is working fine csv format.but when change file name extension .csv to .XLS within in a cell two more values are showing...how to fix please help me in this case sir. – Gowthaman M Sep 21 '17 at 06:43
  • i changed extension .XLS file is created...but single cell multiple values are storing in the excel file... – Gowthaman M Sep 21 '17 at 07:34
  • 2
    @GowthamanM I don't think just changing the file extension is going to work. I suggest you to save JSON as CSV (using above code block) and read the CSV (Using CSVReader) and write it to an XLS (Using apache-poi) [csv_to_xls](http://thinktibits.blogspot.in/2012/12/Convert-CSV-to-XLS-Using-Java-POI-OpenCSV-Example.html). Here you can make the headers bold with black background as well (as you requested earlier). – Sridhar Sep 21 '17 at 09:19
  • @Sridhar Thanks once again sir,...i done using Apache also without your suggestion cannot do.... – Gowthaman M Sep 22 '17 at 11:52
  • CLD.toString() is returning "null" – Pedro Joaquín Nov 26 '19 at 14:56
  • @PedroJoaquín CLD.toString(docs) <- did you passed the docs object here? – Sridhar Nov 28 '19 at 05:17
  • @Sridhar Yes I did – Pedro Joaquín Nov 28 '19 at 16:41
  • @PedroJoaquín please paste the code snipped you used so I can help you – Sridhar Dec 01 '19 at 10:36
  • 1
    @PedroJoaquín I've updated the answer with new library. Hope this fixes the issue you faced. – Sridhar Dec 13 '19 at 12:25
  • Is there a way to get the csv file into a string? (instead of writing to a file). – J. Lui Jan 05 '22 at 22:44
  • @J.Lui you can write to file and then read from that file to a string, or use method `getJsonAsSheet()` to get a 2D Matrix of the sheet and iterate and build your string as you wish. – Sridhar Jan 10 '22 at 12:33
3

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

Jef
  • 869
  • 4
  • 13
  • 27
  • How would you map `{'foo': {'bar': [1, 2, 3]}}` to a spreadsheet? –  Aug 24 '11 at 08:02
  • That's why I said, if the json object is json single object, not json array, the result will be 1 row in the spreadsheet. If the json object is json array, the rows will be same with the json array size. And 1 again, you have to specify what property you want to write into that spreadsheet. If your example, if you want to display the bar (which the value is array), the column will be display maybe java.lang.Array@xxxxx, but it is an array, right. But if the object is [{name: 'a', 'bar' : [1,2,3]}, {name: 'b', 'bar' : [2,3,4]}], and you want to display the name only, it's feasible, right? – Jef Aug 24 '11 at 08:20
-4

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

  • 1
    If the JSON file is a flat array, with all objects having the same field names, then it can be mapped to a two dimensional table. See @Sridhar's example input. – Ron Romero Oct 20 '14 at 20:51