项目场景:
java读取excel文件,读取其中的数字类型转换为字符类型。基于poi5.0版本,setCellType()过时的解决办法。问题描述:
在读取excel文件时,需要读取到String类型的值,这时因为原来的setCellType(CellType.STRING)在poi5.0版本已经弃用,不能转换。@Override
public void run() {
Cell cell = row.getCell(2);
cell.setCellType(CellType.STRING);//setCellType()poi5.0版本已经被弃用
}
解决方案:
这我读取的文件的cell里面的值只有两种格式,一种是数字,一种是文本。所以我只需要判断这两种 Cell cell = row.getCell(2);
CellType cellType = cell.getCellType();
if(cellType == CellType.NUMERIC){
double numericCellValue = cell.getNumericCellValue();//获取数字类型的单元格中的数据NUMERIC
//stripTrailingZeros():去除末尾多余的0,toPlainString():输出时不用科学计数法
String s = new BigDecimal(String.valueOf(numericCellValue)).stripTrailingZeros().toPlainString();
course.setPro_no(s.trim().replaceAll(" ", "")
.replaceAll("/t", "").replaceAll(" ", ""));
}else if(cellType == CellType.STRING){
String s = cell.getStringCellValue();
course.setPro_no(s.trim().replaceAll(" ", "")
.replaceAll("/t", "").replaceAll(" ", ""));
}
注意看代码中的注释。
如果是数字类型的是这样获取
cell.getNumericCellValue();
这时我又发现直接将double类型的numeCellValue强转为String类型的会出现数字变成科学计数法的问题。最后找到解决方法
//stripTrailingZeros():去除末尾多余的0,toPlainString():输出时不用科学计数法
String s = new BigDecimal(String.valueOf(numericCellValue)).stripTrailingZeros().toPlainString();
而字符类型的值就直接这样获取即可
String s = cell.getStringCellValue();