说明:只需要三步就能完成导入Excel
SpringMVC框架搭建和上传多文件上传请参考之前的播客
SpringMVC框架搭建 http://blog.csdn.net/liqingwei168/article/details/79137801
文件上传 http://blog.csdn.net/liqingwei168/article/details/79148388
多文件上传 http://blog.csdn.net/liqingwei168/article/details/79148989
SpringMvc导出Excel文件 http://blog.csdn.net/liqingwei168/article/details/79162359
本篇文章介绍:本篇文章主要是Excel文件的简单导入,为了方便大家看,代码只在controller层中完成。
很简单,只需要三步就能完成
直接进入正题:ExportIntController.java文件
@RequestMapping("toExportInt") @ResponseBody public String toExceptInt(HttpServletRequest request, HttpServletResponse response, MultipartFile file)throws Exception{ //第一步:获取上传的Excel文件的版本,根据不同的版本做处理 InputStream in = file.getInputStream();//转换成输入流 String fileName = file.getOriginalFilename(); if(fileName==null||fileName.length()==0){ return "error"; } String endName = fileName.substring(fileName.lastIndexOf("."),fileName.length());//得到导入文件的后缀名 Workbook workbook = null;//得到excel if(".xls".equals(endName)){ workbook = new HSSFWorkbook(in); //2003版本后缀名 }else if(".xlsx".equals(endName)){ workbook = new XSSFWorkbook(in); //2007版本后缀名 }else{ throw new Exception("error!"); } //第二步:获取上传的Excel文件内容的行和列 Sheet sheet=workbook.getSheetAt(0);//得到第一个shell int totalRows=sheet.getPhysicalNumberOfRows();//得到Excel的行数 int totalCells = 0;//得到Excel的列数(前提是有行数) if(totalRows>=1 && sheet.getRow(0) != null){ totalCells=sheet.getRow(0).getPhysicalNumberOfCells(); } //第三步:遍历行和列把对应的数据封装到实体类 UserFrom中 ,执行添加方法(Excel中的数据可以做到特殊处理) for(int r=1;r<totalRows;r++){//循环Excel行数,从第2行开始。标题不入库 Row row = sheet.getRow(r); if (row == null) continue; UserFrom userFrom = new UserFrom();//实体类 //循环Excel的列 for(int c = 0; c <totalCells; c++){ Cell cell = row.getCell(c); if (null != cell){ if(c==0){ userFrom.setId(cell.getStringCellValue());//用户编号 }else if(c==1){ userFrom.setName(cell.getStringCellValue());//用户名称 }else if(c==2){ userFrom.setAdress(cell.getStringCellValue());//用户地址 } } } userService.addUser(userFrom); } return "success"; }
list.jsp文件,这个页面要自己写跳转方法。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>上传下载功能在线调试</title> </head> <form method="post" action="/exportint/toExportInt" enctype="multipart/form-data"> <input type="file" name="file"/> <button type="submit" >提交</button> </form> <body> <script > </script> </body> </html>
这样Excel的导入就完成了。
效果图:
1.
2.
3.
4.
5.
6.
Ok,这就是SpringMvc的导入。。。。。。。。6666666666