poi5.0版本,setCellType()过时,解决读取数字类型转换为字符类型问题。

项目场景:

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();
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值