【问题标题】:Generate Excel sheet report fron json array in java从java中的json数组生成Excel工作表报告
【发布时间】:2023-03-19 21:05:01
【问题描述】:

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

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
}

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

【问题讨论】:

  • 使用 Apache POI 来做到这一点
  • 您可以为此使用 Apache POI,并使用 XSSFWorkbook、XSSFSheet、Row、Cell 等类。我在下面添加了一个示例代码 sn-p,请检查 - 如果它回答了您的查询,请标记为已回答。
  • 它的工作,可以在附加模式下打开文件@SrikanthA。这样我下次可以继续使用现有数据,

标签: java arrays json excel


【解决方案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);
        }

必需的进口 -

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

【讨论】:

    猜你喜欢
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2014-07-28
    • 1970-01-01
    相关资源
    最近更新 更多