POI 操作Excel導入篇2 -- 獲取單元格Cell、類型獲取數據處理,行列操作

 

本篇收錄針對於POI導入Excel 操作cell的一些常用步驟。

  • 獲取邏輯行
Workbook wb = null;
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(r);
  • 判斷隱藏行和隱藏列
row.getZeroHeight() //判斷隱藏行
sheet.isColumnHidden(j) //判斷隱藏列
  • 遍歷單元格
//遍歷行
for (int r = 0; r <= sheet.getPhysicalNumberOfRows(); r++) {
         Row row = sheet.getRow(r);   
          if(row.getZeroHeight()){
                System.out.println("第"+(r + 1)+"行隱藏行");
                continue;
            }
      //遍歷列
      for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
          if (sheet.isColumnHidden(j)){
             System.out.println("第" + j + "列隱藏列");
             continue;
          } 
          //獲取單元格的值
          String value = checkValue(r,j,row);         
        }
 }
  • 獲取單元格值-數據處理util
public static String checkValue(int r, int j, Row row) {
        Cell cell = row.getCell(j);
        String value = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(cell == null){
            cell = row.createCell(0);
            cell.setCellValue("");
        }
        try {
            switch (cell.getCellType()){
                case Cell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue().trim();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    //處理數字和公式
                        value = String.valueOf(Double.valueOf(cell.getNumericCellValue()));
                        value = value.replaceAll("0+?$", "");
                        value = value.replaceAll("[.]$", "");
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    //處理日期格式的Excel數據
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        value = sdf.format(date);
                    } else {
                        //處理科學計數法
                        double temp = cell.getNumericCellValue();
                        DecimalFormat df = new DecimalFormat("0");
                        value = df.format(temp);
                    }
                    break;
                default:
                    return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("導入失敗!第"+(i + 1)+"行第"+(j + 1)+"列,格式有誤\n");
        }
        return value;
    }

拓展:

  • 獲取單元格格式和對應的值獲取
單元格類型 數值類型和java類型 取值(Cell.getCellType())
文本 1 / CELL_TYPE_STRING cell.getStringCellValue()
公式 2 / CELL_TYPE_FORMULA cell.getNumericCellValue())
數值 0 / CELL_TYPE_NUMERIC cell.getNumericCellValue()
布爾 4 / CELL_TYPE_BOOLEAN cell.getBooleanCellValue()
日期 0 / CELL_TYPE_NUMERIC cell.getDateCellValue()
異常 5 / CELL_TYPE_ERROR cell.getErrorCellValue()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章