在java中生成Excel工作表报告fron json数组

时间:2017-03-06 10:46:58

标签: java arrays json excel

我想生成Excel工作表报告。我有JSON对象,我将转换为JSONarray。这是我的示例代码

.maindiv{       
    overflow: hidden;
}

.sub-menu{
    width: 100%;
    height: 100%;
    overflow-x: scroll;
    padding-bottom:20px;
}

这里我想为for循环中的这三个字段生成excel报告。 请给我一些建议。

1 个答案:

答案 0 :(得分:1)

您可以使用Apache POI并使用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);
        }

必需的进口 -

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;