java通过poi解析excel中的数据

我们在开发中可能会遇到将excel表中的数据存储到数据库中去,这就需要对excel进行解析

在操作过程中用到了poi-3.17.jar包

@Override
	public List<ExcelModel> getTotals(String filePath) {
		InputStream is;
		HSSFWorkbook hssfWorkbook;
		List<ExcelModel> list = null;
		try {
			is = new FileInputStream(filePath);
			hssfWorkbook = new HSSFWorkbook(is);
			ExcelModel excelModel = null;
			list = new ArrayList<>();	
			for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
	            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
	            if (hssfSheet == null) {
	                continue;
	             }
	            // 循环行Row
	             for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
	            	  HSSFRow hssfRow = hssfSheet.getRow(rowNum);
		              if (hssfRow != null) {
		            	 excelModel = new ExcelModel();
	                     HSSFCell id = hssfRow.getCell(0);
	                     HSSFCell teacherName = hssfRow.getCell(1);
	                     HSSFCell major = hssfRow.getCell(2);
	                     HSSFCell title = hssfRow.getCell(3);
	                     HSSFCell describe = hssfRow.getCell(4);
	                     HSSFCell instruction = hssfRow.getCell(5);
	                     HSSFCell exceptResult = hssfRow.getCell(6);
	                     HSSFCell tel = hssfRow.getCell(7);
	                     HSSFCell qq = hssfRow.getCell(8);
	                     
	                     excelModel.setId(getValue(id));
	                     excelModel.setTeacherName(getValue(teacherName));
	                     excelModel.setMajor(getValue(major));
	                     excelModel.setTitle(getValue(title));
	                     excelModel.setDescribe(getValue(describe));
	                     excelModel.setInstruction(getValue(instruction));
	                     excelModel.setExceptResult(getValue(exceptResult));
	                     excelModel.setTel(getValue(tel));
	                     excelModel.setQq(getValue(qq));
	                     
	                     list.add(excelModel);
	                 }
	             }
	         }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
	/**
	 * 类型转换
	 */
	@SuppressWarnings({ "deprecation", "static-access" })
	private String getValue(HSSFCell hssfCell) {
	     if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
	         // 返回布尔类型的值
	         return String.valueOf(hssfCell.getBooleanCellValue());
	     } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
	         // 返回数值类型的值
	         return String.valueOf(hssfCell.getNumericCellValue());
	     } else {
	         // 返回字符串类型的值
	         return String.valueOf(hssfCell.getStringCellValue());
	     }
	}


猜你喜欢

转载自blog.csdn.net/zhaoraolin/article/details/79414495
今日推荐