java使用poi读取Excel数据

@Test
    public void testExcel(){
        String str = "D:\\1.xlsx";
        Workbook workbook = null;
        File file = new File(str);
        System.out.println(file.getName());
        if (file.isFile()&&file.exists()){ //判断文件是否是文件以及存在
            try {
                FileInputStream fileInputStream = new FileInputStream(file);//文件流对象
                try {
                    //可以先判断文件的格式 我的格式是XLSX的 所以我这里省略了
                    workbook = new XSSFWorkbook(fileInputStream);  // 格式为Xlsx 的Excel

                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        workbook = new HSSFWorkbook(fileInputStream);//格式为Xls 的Excel

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Sheet sheet = workbook.getSheetAt(0);//读取第一个sheet页
            int firstRowIndex =sheet.getFirstRowNum(); //第一行
            int lastRowIndex = sheet.getLastRowNum(); //最后一行
            System.out.println();
            System.out.println(firstRowIndex);
            System.out.println(lastRowIndex);
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                System.out.println("rIndex: " + rIndex);
                Row row = sheet.getRow(rIndex); //获得第一行的数据 rIndex=0
                if (row != null) {
                    int firstCellIndex = row.getFirstCellNum();//第一列
                    int lastCellIndex = row.getLastCellNum();//最后一列
                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
                        Cell cell = row.getCell(cIndex); //获得第一行第一列的数据 cIndex=0;
                        if (cell != null) {
                            System.out.println(cell.toString());
                        }
                    }
                }
            }
        }

上述代码如有疑问 欢迎咨询!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值