Excel文件按照指定模板导入数据(用jxl.jar包)

    本文中的方法只适合Excel2003,要读取Excel2007最好使用poi.jar,据说poi.jar还在更新,jxl.jar已经不更新了,处理Excel文件的读写问题最好还是学习poi.jar ,后续会写随笔记录poi.jar的用法。
  读取Excel文件中的内容可以用jxl.jar、poi.jar包,这里只介绍用jxl.jar包的实现方法。首先要导入jxl.jar包,例子中使用的框架是MyBatis+Spring MVC
    思路:为避免向本地上传病毒文件等安全问题,导入文件功能一般不会允许读到文件在本地的路径,因此要读取本地文件中的内容必须先将文件上传到服务器,然后从服务器的路径中读取。因此导入Excel文件数据的过程为:
     (1)上传Excel文件到服务器。
     (2)用jxl.jar包中的方法读取保存在服务器路径中的Excel文件的数据。
     (3)将读取的数据保存到对象中并插入数据库。
     步骤1:文件上传:
     (1)jsp页面的form表单中添加属性:enctype="multipart/form-data"。
       <form:form id="" modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
     (2)form表单中有一个file组件 :
      <input type="file" id="" name="" />
       如果希望点击“文件导入 ”按钮就直接弹出选择文件窗口,不想将文件的input显示出来,可以将input设置成隐藏的,当点击按钮时触发function,在触发的function中设置该文件input的click事件。比如:
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
    <head>
          <script type="text/javascript">
            $(document).ready(function() {
                //数据导入
                 $("#import").click(function(){
                         $("#excelFile").click();
                });
            });
          </script>
    </head>
    <body>
       <form:form id="uploadForm" modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
       <input type="file" id="excelFile" name="" style="display:none"/>  
       <button id="import" class="" type="button"> Excel文件导入 </button>
       </form:form> 
     </body>
</html>
      如果需要对导入文件的格式进行验证,可以写在按钮的onclick事件里:
 
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
    <head>
          <script type="text/javascript">
            $(document).ready(function() {
                 $("#import").click(function(){
                         $("#excelFile").click();
                         checkFile();
                });
            });
          //检查文件类型
          function checkFile(){
                    var array = new Array('xls','xlsx');
                    var filename = $("#uploadfile ").val();
            if(filename == ""){
                  alert("请选择要上传的文件");
                  return false;
             }else {
                    //javaScript的match()方法检索与正则表达式相同格式的字符串,返回一个数组,该数组的第0个元素返回的是匹配文本,其余的元素存放的是与正则表达式的子表达式匹配的文本。获得文件类型除了下面的写法外,还可以用:var extStart=filepath.lastIndexOf(".");fileType = filename.substring(extStart, filename.length);来替代
                    var fileType = filename.match( /^(.*)(.)(.{1,8})$/)[3];//找到文件的后缀
                    var isExist = false;
                    for(i in array){
                         if(fileType.toLowerCase() == array[i].toLowerCase()){
                                 isExist = true;
                                 return true;
                         }
                    }
                   if(isExist == false ){
                         alert("文件类型不正确");
                         return false;
                    }
                   return true;
             }
          }
          </script>
    </head>
    <body>
       <form:form id="uploadForm " modelAttribute="" action="" method="post" enctype="multipart/form-data" class="">
       <input type="file" id="excelFile" name="" style="display:none"/>  
       <button id="import" class="" type="button"> Excel文件导入 </button>
       </form:form> 
     </body>
</html>
     (3)选择完文件且验证过文件类型后,提交表单跳转到导入文件对应的处理方法
          <head>
          <script type="text/javascript">
            $(document).ready(function() {
                //数据导入
                 $("#import").click(function(){
                         $("#excelFile").click();
                         var t = checkFile();
                         if(t){
                         $("#uploadForm").attr("action","${ctx}/app/test/importExcel");
                         $("#uploadForm").submit();
                       }
                });
            });
          </script>
         </head>
 (4)后台类
     //Excel格式数据导入
    @RequestMapping(value = "importExcel")
    public String importExcel(@RequestParam(value="excelFile", required=false) MultipartFile file, RedirectAttributes redirectAttributes, HttpServletResponse response)
     {
           InputStream fis = null;
           String uploadPath = SystemPath.getSysPath() + "WEB-INF/views/app/upload" + File.separator;
           String fileName = file.getOriginalFilename(); //文件名称
           String path = uploadPath + fileName.substring(0, fileName.lastIndexOf(".")) + DateTimeUtil.get_YYYYMMDDHHMMSS(ne  Date())+fileName.substring(fileName.lastIndexOf("."), fileName.length());//为了在服务器中放的文件不重复,修改文件名,在文件名中加上时间
           File uploadFile = new File(path);
           try {
                 file.transferTo(uploadFile);//将本地文件中的内容上传到服务器文件
                 fis = new FileInputStream(path);
                 Workbook wb = Workbook.getWorkbook(fis);//jxl.jar中读取Excel文件内容的方法
                if(!judgeExcelModel(wb)){//judgeExcelModel为判断Excel文件格式的方法,根据具体情况自行添加
                     FileUtils.deleteFile(path);
                     addMessage(redirectAttributes, "Excel格式错误,请下载平台提供的模板");
                }else{
                     int sheet_size = wb.getNumberOfSheets();//工作栏的数量
                     for(int index=0;index<sheet_size;index++){
                                Sheet sheet = wb.getSheet(index);//工作栏的内容
                                for(int i=1;i<sheet.getRows();i++){
                                     Student stu = new Student();
                                     String age = sheet.getCell(0, i).getContents();
                                     String name = sheet.getCell(1, i).getContents();
                                     String class = sheet.getCell(2, i).getContents();
                                     String school = sheet.getCell(3, i).getContents();
                                     stu .setAge(age );
                                     stu .setName(name);
                                     stu .setClass(class);
                                     stu .setSchool(school);
                                     stu Service.insert(stu );
                                }
                     }
                     addMessage(redirectAttributes, "批量导入数据成功");
            FileUtils.deleteFile(path);//导入成功后将服务器中的文件删掉
                }
           } catch (IllegalStateException e) {
                e.printStackTrace();
           } catch (BiffException e) {
                e.printStackTrace();
           }catch (IOException e) {
                e.printStackTrace();
           }finally{
                if(fis != null){
                     try {
                           fis.close();
                     } catch (IOException e) {
                           e.printStackTrace();
                     }
                }
           }
    }
    到这里,已经完成导入Excel文件数据的功能,在具体应用时,应该还需要对插入数据库的各数据进行验证,将验证通过的记录放在list集合中,等所有记录验证结束后再一起将验证通过的数据插入到数据库。
原文地址:https://www.cnblogs.com/bjh1117/p/6437202.html