java 实现excel中的数据导入到数据库表的功能(简单版)

java web项目导入excel获取数据,是实用频率非常高的功能,通过做了几个这样的功能之后,现将此功能总结出了,为了以后自己方便使用,也为大家实现此功能做一个参考.

项目框架

1,后台:spring+springmvc+mybatis

2,前台: bootstrap+jquery+ajax

3,项目管理:maven

说明.excel处理函数需要引入poi的jar包,在pom.xml引入一下代码

  1. <!-- POI -->  
  2. <dependency>  
  3.     <groupId>org.apache.poi</groupId>  
  4.     <artifactId>poi</artifactId>  
  5.     <version>3.8</version>  
  6.     <exclusions>  
  7.         <exclusion>  
  8.             <artifactId>commons-codec</artifactId>  
  9.             <groupId>commons-codec</groupId>  
  10.         </exclusion>  
  11.     </exclusions>  
  12. </dependency>  
  13. <dependency>  
  14.     <groupId>org.apache.poi</groupId>  
  15.     <artifactId>poi-ooxml</artifactId>  
  16.     <version>3.8</version>  
  17. </dependency>  

别的框架大体上也是可以的,只需稍微调整,如有问题,大家可留言讨论

实现的功能说明:将用户信息(姓名,性别,年龄)通过excel上传,并保存到数据库

具体代码如下

1,前台html代码

  1. <form enctype="multipart/form-data" id="batchUpload"  action="user/upload" method="post" class="form-horizontal">    
  2.     <button class="btn btn-success btn-xs" id="uploadEventBtn" style="height:26px;"  type="button" >选择文件</button>  
  3.     <input type="file" name="file"  style="width:0px;height:0px;" id="uploadEventFile">  
  4.     <input id="uploadEventPath"  disabled="disabled"  type="text" placeholder="请选择excel表" style="border: 1px solid #e6e6e6; height: 26px;width: 200px;" >                                           
  5. </form>  
  6. <button type="button" class="btn btn-success btn-sm"  onclick="user.uploadBtn()" >上传</button>  
前台页面效果

excel内容展示


2,JS代码
  1. var User = function(){  
  2.       
  3.     this.init = function(){  
  4.           
  5.         //模拟上传excel  
  6.          $("#uploadEventBtn").unbind("click").bind("click",function(){  
  7.              $("#uploadEventFile").click();  
  8.          });  
  9.          $("#uploadEventFile").bind("change",function(){  
  10.              $("#uploadEventPath").attr("value",$("#uploadEventFile").val());  
  11.          });  
  12.           
  13.     };  
  14.     //点击上传按钮  
  15.     this.uploadBtn = function(){  
  16.         var uploadEventFile = $("#uploadEventFile").val();  
  17.         if(uploadEventFile == ''){  
  18.             alert("请选择excel,再上传");  
  19.         }else if(uploadEventFile.lastIndexOf(".xls")<0){//可判断以.xls和.xlsx结尾的excel  
  20.             alert("只能上传Excel文件");  
  21.         }else{  
  22.             var url =  '/user/upload/';  
  23.             var formData = new FormData($('form')[0]);  
  24.             user.sendAjaxRequest(url,'POST',formData);  
  25.         }  
  26.     };  
  27.       
  28.     this.sendAjaxRequest = function(url,type,data){  
  29.         $.ajax({  
  30.             url : url,  
  31.             type : type,  
  32.             data : data,  
  33.             success : function(result) {  
  34.                 alert( result);  
  35.             },  
  36.             error : function() {  
  37.                 alert( "excel上传失败");  
  38.             },  
  39.             cache : false,  
  40.             contentType : false,  
  41.             processData : false  
  42.         });  
  43.     };  
  44. }  
  45.       
  46.   
  47. var user;  
  48. $(function(){  
  49.     user = new User();  
  50.     user.init();  
  51. });  

3,domain层用户的实体类

  1. /**  
  2.  * @author  liuchj  
  3.  * @version 1.0    
  4.  */  
  5. public class User {  
  6.     private  String name;  
  7.     private String sex;  
  8.     private String age;  
  9.     public String getName() {  
  10.         return name;  
  11.     }  
  12.     public void setName(String name) {  
  13.         this.name = name;  
  14.     }  
  15.     public String getSex() {  
  16.         return sex;  
  17.     }  
  18.     public void setSex(String sex) {  
  19.         this.sex = sex;  
  20.     }  
  21.     public String getAge() {  
  22.         return age;  
  23.     }  
  24.     public void setAge(String age) {  
  25.         this.age = age;  
  26.     }  
  27.         

4,controller层代码

  1. @Controller  
  2. @RequestMapping("/user")  
  3. public class UserController{  
  4.       
  5.     @Autowired  
  6.     private UserService  userService;  
  7.       
  8.     @RequestMapping(value="/upload",method = RequestMethod.POST)  
  9.     @ResponseBody  
  10.     public String  upload(@RequestParam(value="file",required = false)MultipartFile file,HttpServletRequest request, HttpServletResponse response){  
  11.         Sring result = userService.readExcelFile(file);  
  12.         return result;  
  13.     }  
  14. }  
5,service层代码

 1),service层接口

  1. public interface UserService {  
  2.   
  3.     /** 
  4.      * 读取excel中的数据,生成list 
  5.      */  
  6.     String readExcelFile( MultipartFile file);  
  7.   
  8. }  

2),service实现层代码

  1. @Service  
  2. public class MeetingRoomServiceImpl implements MeetingRoomService {  
  3.   
  4. @Override  
  5.     public String readExcelFile(MultipartFile file) {  
  6.         String result ="";  
  7.         //创建处理EXCEL的类  
  8.         ReadExcel readExcel=new ReadExcel();  
  9.         //解析excel,获取上传的事件单  
  10.         List<User> useList = readExcel.getExcelInfo(file);  
  11.         //至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,  
  12.         //和你具体业务有关,这里不做具体的示范  
  13.         if(useList != null && !useList.isEmpty()){  
  14.             result = "上传成功";  
  15.         }else{  
  16.             result = "上传失败";  
  17.         }  
  18.         return result;  
  19.     }  
  20.    

3),excel处理函数

  1. /**  
  2.  * @author liuchj
  3.  * @version 1.0    
  4.  */  
  5. public class ReadExcel {  
  6.     //总行数  
  7.     private int totalRows = 0;    
  8.     //总条数  
  9.     private int totalCells = 0;   
  10.     //错误信息接收器  
  11.     private String errorMsg;  
  12.     //构造方法  
  13.     public ReadExcel(){}  
  14.     //获取总行数  
  15.     public int getTotalRows()  { return totalRows;}   
  16.     //获取总列数  
  17.     public int getTotalCells() {  return totalCells;}   
  18.     //获取错误信息  
  19.     public String getErrorInfo() { return errorMsg; }    
  20.       
  21.   /** 
  22.    * 读EXCEL文件,获取信息集合 
  23.    * @param fielName 
  24.    * @return 
  25.    */  
  26.     public List<User> getExcelInfo(MultipartFile mFile) {  
  27.         String fileName = mFile.getOriginalFilename();//获取文件名  
  28.         try {  
  29.             if (!validateExcel(fileName)) {// 验证文件名是否合格  
  30.                 return null;  
  31.             }  
  32.             boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本  
  33.             if (isExcel2007(fileName)) {  
  34.                 isExcel2003 = false;  
  35.             }  
  36.             List<User> userList = createExcel(mFile.getInputStream(), isExcel2003);  
  37.         } catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         }  
  40.         return userList;  
  41.     }  
  42.     
  43.   /** 
  44.    * 根据excel里面的内容读取客户信息 
  45.    * @param is 输入流 
  46.    * @param isExcel2003 excel是2003还是2007版本 
  47.    * @return 
  48.    * @throws IOException 
  49.    */  
  50.     public List<User> createExcel(InputStream is, boolean isExcel2003) {  
  51.         try{  
  52.             Workbook wb = null;  
  53.             if (isExcel2003) {// 当excel是2003时,创建excel2003  
  54.                 wb = new HSSFWorkbook(is);  
  55.             } else {// 当excel是2007时,创建excel2007  
  56.                 wb = new XSSFWorkbook(is);  
  57.             }  
  58.             List<User> userList = readExcelValue(wb);// 读取Excel里面客户的信息  
  59.         } catch (IOException e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.         return userList;  
  63.     }  
  64.     
  65.   /** 
  66.    * 读取Excel里面客户的信息 
  67.    * @param wb 
  68.    * @return 
  69.    */  
  70.     private List<User> readExcelValue(Workbook wb) {  
  71.         // 得到第一个shell  
  72.         Sheet sheet = wb.getSheetAt(0);  
  73.         // 得到Excel的行数  
  74.         this.totalRows = sheet.getPhysicalNumberOfRows();  
  75.         // 得到Excel的列数(前提是有行数)  
  76.         if (totalRows > 1 && sheet.getRow(0) != null) {  
  77.             this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();  
  78.         }  
  79.         List<User> userList = new ArrayList<User>();  
  80.         // 循环Excel行数  
  81.         for (int r = 1; r < totalRows; r++) {  
  82.             Row row = sheet.getRow(r);  
  83.             if (row == null){  
  84.                 continue;  
  85.             }  
  86.             User user = new User();  
  87.             // 循环Excel的列  
  88.             for (int c = 0; c < this.totalCells; c++) {  
  89.                 Cell cell = row.getCell(c);  
  90.                 if (null != cell) {  
  91.                     if (c == 0) {  
  92.                         //如果是纯数字,比如你写的是25,cell.getNumericCellValue()获得是25.0,通过截取字符串去掉.0获得25  
  93.                         if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
  94.                             String name = String.valueOf(cell.getNumericCellValue());  
  95.                             user.setName(name.substring(0, name.length()-2>0?name.length()-2:1));//名称  
  96.                         }else{  
  97.                             user.setName(cell.getStringCellValue());//名称  
  98.                         }  
  99.                     } else if (c == 1) {  
  100.                         if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
  101.                             String sex = String.valueOf(cell.getNumericCellValue());  
  102.                             user.setSex(sex.substring(0, sex.length()-2>0?sex.length()-2:1));//性别  
  103.                         }else{  
  104.                             user.setSex(cell.getStringCellValue());//性别  
  105.                         }  
  106.                     } else if (c == 2){  
  107.                         if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
  108.                             String age = String.valueOf(cell.getNumericCellValue());  
  109.                             user.setAge(age.substring(0, age.length()-2>0?age.length()-2:1));//年龄  
  110.                         }else{  
  111.                             user.setAge(cell.getStringCellValue());//年龄  
  112.                         }  
  113.                     }  
  114.                 }  
  115.             }  
  116.             // 添加到list  
  117.             userList.add(user);  
  118.         }  
  119.         return userList;  
  120.     }  
  121.       
  122.     /** 
  123.      * 验证EXCEL文件 
  124.      *  
  125.      * @param filePath 
  126.      * @return 
  127.      */  
  128.     public boolean validateExcel(String filePath) {  
  129.         if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {  
  130.             errorMsg = "文件名不是excel格式";  
  131.             return false;  
  132.         }  
  133.         return true;  
  134.     }  
  135.       
  136.     // @描述:是否是2003的excel,返回true是2003   
  137.     public static boolean isExcel2003(String filePath)  {    
  138.          return filePath.matches("^.+\\.(?i)(xls)$");    
  139.      }    
  140.      
  141.     //@描述:是否是2007的excel,返回true是2007   
  142.     public static boolean isExcel2007(String filePath)  {    
  143.          return filePath.matches("^.+\\.(?i)(xlsx)$");    
  144.      }    
  145. }  

猜你喜欢

转载自blog.csdn.net/liuchangjie0112/article/details/79479362