Apache POI操作xlsx

一、读取xlsx文件

1、pom.xml

<dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
</dependencies>

2、测试类

public class PoiDemo {
    @Test
    public void exportExcel()throws Exception{
        //获取类路径下文件的文件流
        InputStream is = Class.forName("com.mytest.PoiDemo").getClassLoader().getResourceAsStream("poi.xlsx");
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        //获取工作表,即可以根据工作表的顺序获取,也可以根据工作表的名称获取
        XSSFSheet sheet = workbook.getSheetAt(0);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //遍历工作表获的行对象
        for (Row row : sheet) {
            //遍历行对象获取单元格对象
            for (Cell cell : row) {
                //判断是否为数字
                if (cell.getCellType()== XSSFCell.CELL_TYPE_NUMERIC){
                    //判断是否为日期
                    if (HSSFDateUtil.isCellDateFormatted(cell)){
                        double dateDouble = cell.getNumericCellValue();
                        //获取Date对象
                        Date javaDate = HSSFDateUtil.getJavaDate(dateDouble);
                        //转为字符串格式日期
                        String formatStr = dateFormat.format(javaDate);
                        System.out.print(formatStr+" ");
                    }else {
                        double numericCellValue = cell.getNumericCellValue();
                        System.out.print(numericCellValue+" ");
                    }
                    //判断是否为布尔值
                } else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN){
                    System.out.print(cell.getBooleanCellValue()+" ");
                    //判断是否为公式
                }else if (cell.getCellType()==Cell.CELL_TYPE_FORMULA){
                    System.out.println(cell.getCellFormula().toString());
                }else{
                    String stringCellValue = cell.getStringCellValue();
                    System.out.print(stringCellValue+" ");
                }

            }
            System.out.println();
        }
        workbook.close();
        is.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值