java实现读取excel表格数据

话不多说,直接上代码:

一、添加依赖:


   org.apache.poi
   poi-ooxml
   3.16

二、判断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

2、读取2003Excel

/**
	 * 处理Excel的数据 2003
	 * @autor wzj
	 * @return 
	 */
	public static List getExcel2003(String filepath) throws IOException {
		Workbook workbook = new HSSFWorkbook(new FileInputStream(filepath));
		List 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 map=new HashMap<>();
				Row row=sheet.getRow(rowNum);
				if (row==null) {
	            	continue;
				}
				for (int i = 0; i  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");

你可能感兴趣的:(java,excel)