2017-03-06 24 views
2

我想生成Excel表單報表。我有JSON對象,我將被轉換成JSONarray。下面是我的示例代碼在java中生成Excel表單報表fron json數組

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報表。 請給我建議。

+0

使用Apache POI來做到這一點 –

+0

您可以爲此使用Apache POI並使用XSSFWorkbook,XSSFSheet,Row,Cell等類。我在下面添加了一個示例代碼片段,請檢查 - 如果它回答您的查詢,請將其標記爲已回答。 –

+0

它的工作,是否可以在追加模式@SrikanthA中打開文件。所以我可以繼續下一次現有的數據, –

回答

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;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;