我想生成 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 并使用 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;
关于java - 在java中从json数组生成Excel工作表报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42623581/