官网推荐Date处理-使用POI读取单元格的内容

POI-官网-API地址:Busy Developers' Guide to HSSF and XSSF Features (apache.org)

http://poi.apache.org/components/spreadsheet/quick-guide.html

因为项目中使用到POI获取单元格的内容,。

刚开始也是去百度  怎么做,后来发现官网上的更加好用。所有记录一下,看到的也可以少走些弯路

不废话,直接贴官网代码,需要导入apach 的poi 的相应的包。

代码中有两种方式

第一种:啥都不用管,直接把单元格给 DataFormatter ,它会帮你自动根据单元格的类型并获取值转成字符返回。(刚开始做的时候没看官网,不知道这种方式,简单的一批)。

第二种:自己根据单元格的类型,使用对应的get方法获取值,这种做法好处是自己可以根据单元格的类型进行后续处理。(

如果你没有特殊处理的要求,建议使用第一种)

下面由我自己的英语和百度翻译的结合解析官方的注释

DataFormatter formatter = new DataFormatter();
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
    for (Cell cell : row) {
        //下面这几行应该是获取单元的位置比如:A1
        CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
        System.out.print(cellRef.formatAsString());
        System.out.print(" - ");
 
        //第一种方式 :
        // get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
        //获取显示在单元格中的文本 通过获取单元格的值,并且可以适用于任何数据格式。
        String text = formatter.formatCellValue(cell);
        System.out.println(text);
 
        //第二种方式:
        // Alternatively, get the value and format it yourself
        // 或者,获取值以后自行格式化
        switch (cell.getCellType()) {
            case CellType.STRING:
                System.out.println(cell.getRichStringCellValue().getString());
                break;
            case CellType.NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.println(cell.getDateCellValue());
                } else {
                    System.out.println(cell.getNumericCellValue());
                }
                break;
            case CellType.BOOLEAN:
                System.out.println(cell.getBooleanCellValue());
                break;
            case CellType.FORMULA:
                System.out.println(cell.getCellFormula());
                break;
            case CellType.BLANK:
                System.out.println();
                break;
            default:
                System.out.println();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值