话不多说,直接上代码:

一、添加依赖:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.16</version>
</dependency>

二、判断excle类型,并调用相应的方法

/**
	 * 获取Excel工作蒲 
	 * @param filepath 文件路径
	 * @return
	 */
	public static void getExcel(String filepath) throws IOException {
		String filetype=getExcelType(filepath);
			if (filetype.equals("2003")) {//xls文件
				getExcel2003(filepath);
			} else if (filetype.equals("2007")) {//xlsx文件 
				getExcel2007(filepath);
			}
	}

/**
	 * 判断excel文件版本
	 * @param filePath 文件路径
	 * @return
	 */
	public static String getExcelType(String filePath) {
		String type="";
		if(filePath.matches("^.+\\.(?i)(xlsx)$")){
			type="2007";
		}else if (filePath.matches("^.+\\.(?i)(xls)$")) {
			type="2003";
		}
        return type;
    }

1、读取2007Excel

/**
	 * 获取Excel工作蒲 2007
	 * @param filepath 文件路径
	 * @return
	 */
	public static void getExcel2007(String filepath)  throws IOException {
			//创建工作簿对象
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(filepath));
			//获取工作簿下sheet的个数
			int sheetNum = xssfWorkbook.getNumberOfSheets();
			System.out.println("该excel文件中总共有:"+sheetNum+"个sheet");
			//遍历工作簿中的所有数据
			for(int i = 0;i<sheetNum;i++) {
				//读取第i个工作表
				System.out.println("读取第"+(i+1)+"个sheet");
				XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
				//获取最后一行的num,即总行数。此处从0开始
				int maxRow = sheet.getLastRowNum();
				for (int row = 0; row <= maxRow; row++) {
					//获取最后单元格num,即总单元格数 ***注意:此处从1开始计数***
					int maxRol = sheet.getRow(row).getLastCellNum();
					System.out.println("--------第" + row + "行的数据如下--------");
					for (int rol = 0; rol < maxRol; rol++){
						System.out.print(sheet.getRow(row).getCell(rol) + "  ");
					}
					System.out.println();
				}
			}
	}

2、读取2003Excel

/**
	 * 处理Excel的数据 2003
	 * @autor wzj
	 * @return 
	 */
	public static List<String[]> getExcel2003(String filepath) throws IOException {
		Workbook workbook = new HSSFWorkbook(new FileInputStream(filepath));
		List<String[]> list=new ArrayList<>();
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {//获取每个sheet
            Sheet sheet = workbook.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            //方法一:放入list集合
            for(int r = 0;r<sheet.getLastRowNum()+1;r++){
				Row headerRow=sheet.getRow(r);//获取每一行数据
				if (headerRow==null) {
					continue;
				}
				String[] headers=new String[headerRow.getLastCellNum()];//获取每一列并创建一个数组存放数组中
				for (int i = 0; i <headerRow.getLastCellNum(); i++) {
					headers[i]=getValue(headerRow.getCell(i));
				}
				list.add(headers);
			}
			//方法二:放入map集合
            /*for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {//获取数据行
            	Map<String, String> map=new HashMap<>();
				Row row=sheet.getRow(rowNum);
				if (row==null) {
	            	continue;
				}
				for (int i = 0; i <row.getLastCellNum(); i++) {
					map.put(headers[i], getValue(row.getCell(i)));//将数据存放到map里面 key为表头的值
				}
				list.add(map);
			}*/
		}
		for (String[] items : list){
			Arrays.asList(items).forEach(item -> System.out.println(item));
		}
		return list;
	}

/**
	 * 转换数据为String
	 * @param cell 
	 * @return
	 */
	public static String getValue(Cell cell){
		if(cell==null){
    		return "";
    	}else{
	        if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {//Boolean类型
	            return String.valueOf(cell.getBooleanCellValue());
	        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {//Number类型
	        	double d=cell.getNumericCellValue();
	        	//如果直接tostring,数组大的将会转为科学计数法 1.0E10 所以需要format
	        	DecimalFormat df=new DecimalFormat("#");
	        	return df.format(d);
	        } else {
	            return String.valueOf(cell.getStringCellValue());
	        }
    	}
	}

三、在主方法或自定义的接口下调用工具测试:

ExcelUtils.getExcel("C://Users//dell//Desktop//123.xls");

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐