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

我想生成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报告。 请给我build议。

您可以为此使用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 –

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;