swapnil kolapkar
swapnil kolapkar

Reputation: 25

Generate Excel sheet report fron json array in java

I want to generate excel sheet report. I having JSON object that i will be converted into JSONarray. Here is my sample code

JSONObject jsonObj = new JSONObject(jsonString.toString()); //convert to json object
JSONArray objSearchOrdersDto = jsonObj.getJSONArray("objSearchOrdersDto"); // convert to json array

for (int i = 0; i < objSearchOrdersDto.length(); ++i) 
{

    JSONObject rec = objSearchOrdersDto.getJSONObject(i);
    int OrderNumber = rec.getInt("OrderNumber");
    String strStatusType = rec.getString("strStatusType");
    int OrgUnitId = rec.getInt("OrgUnitId");
    System.out.println(OrderNumber+"\t"+strStatusType+"\t"+OrgUnitId); //want to excel file for this three field
}

Here i want to generate excel report only for these three field in for loop. Please give me suggestion.

Upvotes: 2

Views: 8252

Answers (1)

Srikanth Balaji
Srikanth Balaji

Reputation: 2718

You can use Apache POI for this and use classes like XSSFWorkbook, XSSFSheet, Row, Cell.

JSONObject jsonObj = new JSONObject(jsonString.toString()); //convert to json object
JSONArray objSearchOrdersDto = jsonObj.getJSONArray("objSearchOrdersDto"); // convert to json array


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

        int rowCount = 0;
        for (int i = 0; i < objSearchOrdersDto.length(); ++i)
        {
            JSONObject rec = objSearchOrdersDto.getJSONObject(i);
            int OrderNumber = rec.getInt("OrderNumber");
            String strStatusType = rec.getString("strStatusType");
            int OrgUnitId = rec.getInt("OrgUnitId");

            Row row = sheet.createRow(++rowCount);
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(OrderNumber);
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(strStatusType);
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(OrgUnitId);
            System.out.println(OrderNumber+"\t"+strStatusType+"\t"+OrgUnitId); //want to excel file for this three field
        }


        try (FileOutputStream outputStream = new FileOutputStream("Report.xlsx")) {
            workbook.write(outputStream);
        }

Required Imports -

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Upvotes: 2

Related Questions