天天看点

POI cell.setCellType()过时的替代方案

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站 ​​点击跳转浏览。​​

今天用poi开发中遇到一个问题,找了很久找到答案

问题描述

目的是将数字和字符创类型都转换成字符串类型

一开始用的是

public static String getValue(Cell cell) {
    String cellValue = "";
    if (cell == null) {
      return cellValue;
    }
    // 把数字当成String来读,避免出现1读成z`1.0的情况

    cell.setCellType(CellType.STRING);
    if (cell.getCellType() == CellType.BOOLEAN) {
      cellValue = String.valueOf(cell.getBooleanCellValue());
    } else if (cell.getCellType() == CellType.NUMERIC) {
      cellValue = String.valueOf(cell.getNumericCellValue());
    } else if (cell.getCellType() == CellType.STRING) {
      cellValue = String.valueOf(cell.getStringCellValue());
    } else if (cell.getCellType() == CellType.FORMULA) {
      cellValue = String.valueOf(cell.getCellFormula());
    } else if (cell.getCellType() == CellType.BLANK) {
      cellValue = " ";
    } else if (cell.getCellType() == CellType.ERROR) {
      cellValue = "非法字符";
    } else {
      cellValue = "未知类型";
    }
    return cellValue;
  }      

这种方法,但是这个中间setCellType()方法过时所以只能找其他方法来代替

POI cell.setCellType()过时的替代方案
Cell cell = row.getCell(j);
        DataFormatter dataFormatter = new DataFormatter();
        String value = dataFormatter.formatCellValue(cell);