pom.xml
关键jar包如下:
commons-fileupload
commons-fileupload
1.3.3
org.apache.poi
poi-ooxml
3.17
其中, commons-fileupload 适用于文件上传和下载的jar包, poi-ooxml 是支持操作excel文件的jar包.
spring-web.xml
需要在spring的配置文件中配置上传文件的解析器.
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
单个excel文件上传
前端代码(使用thymeleaf模板引擎)
单个excel文件上传
还可以使用 直接请求 后台controller 的方法:
window.location.href = 请求后台的路径
后端代码
这里使用了 POIUtil 工具类解析excel文件, 传送门
/*** * 从web页面导入单个excel文件
*
*@paramexcelFile 上传的excel文件
*@paramrequest Request对象
*@return内容
*@throwsIOException*/@PostMapping("/excel/import")
@ResponseBodypublic List importExcel(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request) throwsIOException {//1: 转存文件
if (!excelFile.isEmpty()) {/*** 这里的getRealPath("/")是打包之后的项目的根目录。
* 也就是 target\项目名-1.0-SNAPSHOT\*/String storePath= request.getSession().getServletContext().getRealPath("/") + "upload/temp/";
excelFile.transferTo(new File(storePath +excelFile.getOriginalFilename()));
}//2: 解析excel数据
List excelData = POIUtil.readExcelFile(excelFile, 1);
List userInfoList = new ArrayList<>();for(String[] arr : excelData) {
ExcelUserInfo userInfo= newExcelUserInfo();
userInfo.setId(Integer.valueOf(arr[0]));
userInfo.setName(arr[1]);
userInfo.setAge(Integer.valueOf(arr[2]));
userInfoList.add(userInfo);
}//3: 输出excel数据
returnuserInfoList;
}
多个excel文件上传
前端代码(使用thymeleaf模板引擎)
div>
多个excel文件上传