java利用poi本地读取excel

  |   0 评论   |   0 浏览
public static void main(String[] args) throws Exception {
		
	//excel文件路径
        String excelPath = "D:\\统计表.xlsx";
        
        //初始化File
        File excel = new File(excelPath);
        
        //判断文件是否存在
        if (!excel.isFile() || !excel.exists()) {
        	System.out.println("找不到指定的文件");
        	return;
        }
        
        //获取文件后缀
        String suffix = excel.getName().split("\\.")[1];
        
        //定义工作簿
        Workbook wb;
        
        //根据文件后缀(xls/xlsx)进行判断初始化 工作簿
        if ( "xls".equals(suffix)){
            FileInputStream fis = new FileInputStream(excel);   //文件流对象
            wb = new HSSFWorkbook(fis);
        }else if ("xlsx".equals(suffix)){
            wb = new XSSFWorkbook(excel);
        }else {
            System.out.println("文件类型错误!");
            return;
        }

        //开始解析:第一个sheet页
        Sheet sheet = wb.getSheetAt(0);
        
        //第一行下标:  第一行是标题,所以不读(根据文件情况,有可能多个标题,灵活修改)
        int firstRowIndex = sheet.getFirstRowNum()+1;
        
        //最后一行下标
        int lastRowIndex = sheet.getLastRowNum();
        
        
        //遍历行
        for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
        	Row row = sheet.getRow(rIndex);
            if (row != null) {
            	int firstCellIndex = row.getFirstCellNum();
                int lastCellIndex = row.getLastCellNum();
                
                //遍历列
                for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
                    Cell cell = row.getCell(cIndex);
                    
                    //每个单元格
                    if (cell != null) {
                    	
                    	
                    	
                    }
                }
            }
        }
        
        //关闭工作薄
        wb.close();
        
	}