消费端代码
//excel数据导入数据库 @PostMapping("/impNews") public String importNews(@RequestParam(value = "file") MultipartFile file, Map<String,Object>map) throws IOException { Resource invoicesResource = file.getResource(); // System.out.println(file.getResource()); LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(); parts.add("file", invoicesResource); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders); String response = restTemplate.postForObject(url + "/impNews", httpEntity, String.class); if ("success".equals(response)){ return "redirect:/"; }else{ map.put("msg","导入出错,请检查后重试"); return "redirect:/"; } }服务端代码
/* * excel文件导入数据库 * */ @PostMapping("/impNews") public String impNews( MultipartFile file){ List<News> news = ExcelUtils.importData(file, 1, News.class); newsService.insertAll(news); return "success"; }其中的importData是一个工具类中的导入Excel的方法,代码如下:
* * @Title: importData * @Description: 导入excle 数据 * @param file 文件 * @param headerRows 忽略头行数 * @param pojoClass 转换的实体 * @return List<User> 返回的集合 */ public static <T> List<T> importData(MultipartFile file, Integer headerRows, Class<T> pojoClass){ if (file == null) { return null; } ImportParams params = new ImportParams(); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return list; }希望能够帮助到有类似需求的朋友!!