How to convert json file to excel file in java

Yash Gudhka :

I,m given a problem to convert JSON file to excel file, in short to convert JSON data to excel data. Tried mapping JSON keys and values but can't do it.

Tried mapping JSON keys and values but can't do it. I have already used apache POI api.

public class jsontoexcel {

    public static void main(String[] args) throws IOException,JSONException {
        jsontoexcel json4=new jsontoexcel();
        JSONObject json=json4.ReadJson();
        JSONArray array =new JSONArray();
        JSONObject rowjson=json.getJSONArray("rows").getJSONObject(0);

        XSSFWorkbook workbook=new XSSFWorkbook();
        XSSFSheet sheet=workbook.createSheet("Company Details");

        int len=rowjson.length();
        String[] RowArr=new String[len];
        Iterator<String> keys = rowjson.keys();
        int i=0;
        while(keys.hasNext())
        {
            RowArr[i]=keys.next();
            System.out.print("key:"+keys);
            i++;
        }
        List<String> slist= new ArrayList<String>();
        slist=json.get(rowjson.toString(keys));

         FileOutputStream out=new FileOutputStream(new File("C:\\code\\eclipse\\jsontoexcel\\src\\output.xlsx"));

         createHeaderRow(sheet, RowArr);
         workbook.write(out);
         out.close();



      //  Map<String,Object> map=new Map<String,Object>();      

    }

    public static void createHeaderRow(XSSFSheet sheet, String[] RowArr)
    {
        Row row=sheet.createRow(0);
        for(int i=0;i<RowArr.length-1;i++)
        {
            Cell cellTitle=row.createCell(i+1);
            String cellVal=RowArr[i];
            System.out.print("Cell data" + cellVal);
        }
    }
}

I expect the output to be stored in an excel file. The headers are getting printed but not the values.

Michał Ziober :

Do not generate Excel file until you really have to. In case, you want to generate data without any specific formatting, charts, macros, etc. just generate CSV file with pure data. To read JSON and generate CSV you can use Jackson library which supports these two data formats. Just assume your JSON looks like below:

{
  "rows": [
    {
      "id": 1,
      "name": "Vika",
      "age": 27
    },
    {
      "id": 2,
      "name": "Mike",
      "age": 28
    }
  ]
}

You, need to create POJO model which fits to that structure, deserialise JSON to objects and serialise objects to CSV format. Example solution, could look like below:

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.File;
import java.util.List;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper jsonMapper = new ObjectMapper();
        Response response = jsonMapper.readValue(jsonFile, Response.class);

        CsvMapper csvMapper = new CsvMapper();
        CsvSchema schema = csvMapper.schemaFor(Item.class).withHeader();
        SequenceWriter sequenceWriter = csvMapper.writer(schema).writeValues(System.out);
        sequenceWriter.writeAll(response.getRows());
    }
}

class Response {
    private List<Item> rows;

    // getters, setters
}

@JsonPropertyOrder({"id", "name", "age"})
class Item {

    private int id;
    private String name;
    private int age;

    // getters, setters
}

Above code prints:

id,name,age
1,Vika,27
2,Mike,28

See also:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166094&siteId=1