在excel中,使用java,POI jar忽略非空行的空单元格

时间:2017-01-11 07:19:07

标签: java json xml excel apache-poi

使用JAVA,POI的Excel到Json转换

  
    

问题:非空行中的空单元格被忽略。

         
      

我正在尝试通过java将excel文件转换为Json。A2 and B2 cells are empty but these cells are negleted i want even these cells to be counted and return an empty string

    
  

output obtained, the 2nd row starts from C2 by neglecting A2 and B2 which has empty values

public static String ExcelToJsonConverter(String filePath)抛出异常{

try {


    FileInputStream inp = new FileInputStream(filePath);
    Workbook workbook = WorkbookFactory.create(inp);

    Sheet sheet = workbook.getSheetAt(0);

    JSONArray rows = new JSONArray();

    int coun = 0;


    for (Iterator < Row > rowsIT = sheet.rowIterator(); rowsIT.hasNext();)

    {

        Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();


        JSONArray cells = new JSONArray();
        for (Iterator < Cell > cellsIT = row.cellIterator(); cellsIT.hasNext();) {
            coun++;
            Cell cell = cellsIT.next();


            String val = "";


            if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
                System.out.println("Formula is " + cell.getCellFormula());
                switch (cell.getCachedFormulaResultType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                        val = Double.toString(cell.getNumericCellValue());
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                        val = cell.getStringCellValue();
                        break;
                }
            } else if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {

                val = " ";

            } else {

                val = formatter.formatCellValue(cell);

            }
enter code here
            cells.put(val);
        }
        jRow.put("", cells);
        rows.put(jRow);

    }


    json.put("", rows);


} catch (Exception e) {
    //throw new BsfConstraintViolationException("Please Upload a valid file."+e.getMessage());
    throw new BsfConstraintViolationException("Please Upload a valid file using Download Default BOQ option");
}

String formatJson = json.toString().replace("\"\":", "");

formatJson = formatJson.toString().replace("{", "");
formatJson = formatJson.toString().replace("}", "");
formatJson = formatJson.substring(1, formatJson.length() - 1);


return formatJson;

}

预先感谢所有

0 个答案:

没有答案