1.引入poi的依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
2.jsp页面编写上传文件
<form action="http://localhost:8085/mango/pay/lotPayThirdAccount/getFile" enctype="multipart/form-data" method="post"> 选择一个文件: <input type="file" name="excelFile"/> <br/><br/> <input type="submit" value="上传" /> </form>
3.后台接收文件(仅有接收步骤,详细API自己看文档)
@RequestMapping(value = "/getFile", method = RequestMethod.POST) public GenericResult<?> getFile(@RequestParam(value="excelFile")MultipartFile file,HttpServletRequest req) throws IOException{ // 获取临时存储路径以及重命名文件 String filePath = req.getSession().getServletContext().getRealPath("/")+"WEB-INF/upload"; String fileName = file.getOriginalFilename(); fileName = DateUtil.dateToString(new Date(), DateUtil.YYYYMMDDHHMMSS)+fileName; System.err.println("文件上传的临时文件夹:"+filePath); // 校验目录,不存在则创建 File targetFile = new File(filePath, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { //将前台传过来的file文件写到targetFile中. file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } String absolutePath = filePath + "/" + fileName; InputStream fis = new FileInputStream(absolutePath); Workbook wb = null; try { wb = WorkbookFactory.create(fis); } catch (InvalidFormatException e) { e.printStackTrace(); }
Sheet sheet = wb.getSheetAt(0); int totalRowNum = sheet.getLastRowNum(); System.out.println(totalRowNum); return null; }
以上是简单的一个接收流程,如果WorkbookFactory.create(fis)包内存溢出的错误, eclipse的vm配置为:
-Xms256M -Xmx512M -XX:PermSize=256m -XX:MaxPermSize=512m
即可解决。