@PostMapping("/waterTest/importData") public void importData(MultipartFile file, HttpServletRequest req) throws IOException { InputStream inputStream = file.getInputStream(); try { //获取到的list集合 List<List<Object>> list = getListByExcel(inputStream); } catch (Exception e) { e.printStackTrace(); } } /** * @Description:获取IO流中的数据,组装成List<List<Object>>对象 * @param in,fileName * @return * @throws IOException */ public static List<List<Object>> getListByExcel(InputStream in) throws Exception{ List<List<Object>> list = null; //创建Excel工作薄 Workbook work = new HSSFWorkbook(in); if(null == work){ throw new Exception("创建Excel工作薄为空!"); } Sheet sheet = null; //页数 Row row = null; //行数 Cell cell = null; //列数 list = new ArrayList<List<Object>>(); //遍历Excel中所有的sheet sheet = work.getSheetAt(0); //遍历当前sheet中的所有行 for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) { row = sheet.getRow(j); if(row==null||row.getFirstCellNum()==j){continue;} //遍历所有的列 List<Object> li = new ArrayList<Object>(); for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) { cell = row.getCell(y); li.add(getValue(cell)); } if(getValue(row.getCell(0))!=null&&!getValue(row.getCell(0)).equals("")){ list.add(li); } } return list; } /** * @Description:对表格中数值进行格式化 * @param cell * @return */ //解决excel类型问题,获得数值 public static String getValue(Cell cell) { String value = ""; if(null==cell){ return value; } switch (cell.getCellType()) { //数值型 case Cell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { //如果是date类型则 ,获取该cell的date值 Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); value = format.format(date);; }else {// 纯数字 //BigDecimal big=new BigDecimal(cell.getNumericCellValue()); //value = big.toString(); value= String.valueOf(cell.getNumericCellValue()); //解决1234.0 去掉后面的.0 /* if(null!=value&&!"".equals(value.trim())){ String[] item = value.split("[.]"); if(1<item.length&&"0".equals(item[1])){ value=item[0]; } }*/ } break; //字符串类型 case Cell.CELL_TYPE_STRING: value = cell.getStringCellValue().toString(); break; // 公式类型 case Cell.CELL_TYPE_FORMULA: //读公式计算值 value = String.valueOf(cell.getNumericCellValue()); if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串 value = cell.getStringCellValue().toString(); } break; // 布尔类型 case Cell.CELL_TYPE_BOOLEAN: value = " "+ cell.getBooleanCellValue(); break; default: value = cell.getStringCellValue().toString(); } if("null".endsWith(value.trim())){ value=""; } return value; }
excel导入存到数据库(老项目 poi)
最新推荐文章于 2023-10-19 19:15:58 发布