【POI】——获得单元格的值,并转化成字符串

来源:互联网 发布:linux openssl devel 编辑:程序博客网 时间:2024/06/13 09:40

本篇文章分享一些在做导入导出EXCEL功能时用到的工具类的一些代码。

/**     * @param cell     * @return     */    public static String getStringValueFromCell(Cell cell) {        SimpleDateFormat sFormat = new SimpleDateFormat("MM/dd/yyyy");        DecimalFormat decimalFormat = new DecimalFormat("#.#");        String cellValue = "";        if(cell == null) {            return cellValue;        }        else if(cell.getCellType() == Cell.CELL_TYPE_STRING) {            cellValue = cell.getStringCellValue();        }        else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {            if(HSSFDateUtil.isCellDateFormatted(cell)) {                double d = cell.getNumericCellValue();                Date date = HSSFDateUtil.getJavaDate(d);                cellValue = sFormat.format(date);            }            else {                                cellValue = decimalFormat.format((cell.getNumericCellValue()));            }        }        else if(cell.getCellType() == Cell.CELL_TYPE_BLANK) {            cellValue = "";        }        else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {            cellValue = String.valueOf(cell.getBooleanCellValue());        }        else if(cell.getCellType() == Cell.CELL_TYPE_ERROR) {            cellValue = "";        }        else if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {            cellValue = cell.getCellFormula().toString();        }        return cellValue;    }

如果直接使用

cell.getStringCellValue();

当单元格的格式为数字或其他格式时,这句代码就会报错,在开发时一定要注意。

0 1
原创粉丝点击