maven+springmvc+POI导入Excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yh869585771/article/details/79904521

说明

POI可以对2003-和2007+版本的Excel文件做导入导出操作,本章只简单介绍对Excel文件的导入操作。

Excel文件的上传处理处理请求,依然使用SpringMvc中的MultipartRequest方式处理。前端JSP中使用传统form表单提交方式。


环境

Maven+JDK6+ Tomcat7.x + Spring4.x.x


说明

 jquery.form.js 的版本要3.23左右
  • 1
  • 2

ImportExcelUtil.Java:Excel解析工具类

UploadExcelControl.java :处理来自页面的请求控制器

InfoVo.java :将Excel转换为对象存储

main.jsp:前端访问页

……..


  • pom.xml:提供poi.jar的依赖
        <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>

  • ImportExcelUtil.java(Excel解析工具类)
[java]  view plain  copy
  1. package com.poiexcel.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.text.DecimalFormat;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11. import org.apache.poi.ss.usermodel.Cell;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16.   
  17.   
  18. public class ImportExcelUtil {  
  19.       
  20.     private final static String excel2003L =“.xls”;    //2003- 版本的excel  
  21.     private final static String excel2007U =“.xlsx”;   //2007+ 版本的excel  
  22.       
  23.     /** 
  24.      * 描述:获取IO流中的数据,组装成List<List<Object>>对象 
  25.      * @param in,fileName 
  26.      * @return 
  27.      * @throws IOException  
  28.      */  
  29.     public  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
  30.         List<List<Object>> list = null;  
  31.           
  32.         //创建Excel工作薄  
  33.         Workbook work = this.getWorkbook(in,fileName);  
  34.         if(null == work){  
  35.             throw new Exception(“创建Excel工作薄为空!”);  
  36.         }  
  37.         Sheet sheet = null;  
  38.         Row row = null;  
  39.         Cell cell = null;  
  40.           
  41.         list = new ArrayList<List<Object>>();  
  42.         //遍历Excel中所有的sheet  
  43.         for (int i = 0; i < work.getNumberOfSheets(); i++) {  
  44.             sheet = work.getSheetAt(i);  
  45.             if(sheet==null){continue;}  
  46.               
  47.             //遍历当前sheet中的所有行  
  48.             for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {  
  49.                 row = sheet.getRow(j);  
  50.                 if(row==null||row.getFirstCellNum()==j){continue;}  
  51.                   
  52.                 //遍历所有的列  
  53.                 List<Object> li = new ArrayList<Object>();  
  54.                 for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
  55.                     cell = row.getCell(y);  
  56.                     li.add(this.getCellValue(cell));  
  57.                 }  
  58.                 list.add(li);  
  59.             }  
  60.         }  
  61.         work.close();  
  62.         return list;  
  63.     }  
  64.       
  65.     /** 
  66.      * 描述:根据文件后缀,自适应上传文件的版本  
  67.      * @param inStr,fileName 
  68.      * @return 
  69.      * @throws Exception 
  70.      */  
  71.     public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
  72.         Workbook wb = null;  
  73.         String fileType = fileName.substring(fileName.lastIndexOf(”.”));  
  74.         if(excel2003L.equals(fileType)){  
  75.             wb = new HSSFWorkbook(inStr);  //2003-  
  76.         }else if(excel2007U.equals(fileType)){  
  77.             wb = new XSSFWorkbook(inStr);  //2007+  
  78.         }else{  
  79.             throw new Exception(“解析的文件格式有误!”);  
  80.         }  
  81.         return wb;  
  82.     }  
  83.   
  84.     /** 
  85.      * 描述:对表格中数值进行格式化 
  86.      * @param cell 
  87.      * @return 
  88.      */  
  89.     public  Object getCellValue(Cell cell){  
  90.         Object value = null;  
  91.         DecimalFormat df = new DecimalFormat(“0”);  //格式化number String字符  
  92.         SimpleDateFormat sdf = new SimpleDateFormat(“yyy-MM-dd”);  //日期格式化  
  93.         DecimalFormat df2 = new DecimalFormat(“0.00”);  //格式化数字  
  94.           
  95.         switch (cell.getCellType()) {  
  96.         case Cell.CELL_TYPE_STRING:  
  97.             value = cell.getRichStringCellValue().getString();  
  98.             break;  
  99.         case Cell.CELL_TYPE_NUMERIC:  
  100.             if(“General”.equals(cell.getCellStyle().getDataFormatString())){  
  101.                 value = df.format(cell.getNumericCellValue());  
  102.             }else if(“m/d/yy”.equals(cell.getCellStyle().getDataFormatString())){  
  103.                 value = sdf.format(cell.getDateCellValue());  
  104.             }else{  
  105.                 value = df2.format(cell.getNumericCellValue());  
  106.             }  
  107.             break;  
  108.         case Cell.CELL_TYPE_BOOLEAN:  
  109.             value = cell.getBooleanCellValue();  
  110.             break;  
  111.         case Cell.CELL_TYPE_BLANK:  
  112.             value = ”“;  
  113.             break;  
  114.         default:  
  115.             break;  
  116.         }  
  117.         return value;  
  118.     }  
  119.       
  120.   
  121. }  


  • UploadExcelControl.java (控制器)
[java]  view plain  copy
  1. package com.poiexcel.control;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.springframework.stereotype.Controller;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.multipart.MultipartFile;  
  15. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  16.   
  17. import com.poiexcel.util.ImportExcelUtil;  
  18. import com.poiexcel.vo.InfoVo;  
  19.   
  20. @Controller  
  21. @RequestMapping(“/uploadExcel/*”)    
  22. public class UploadExcelControl {  
  23.       
  24.     /**  
  25.      * 描述:通过传统方式form表单提交方式导入excel文件  
  26.      * @param request  
  27.      * @throws Exception  
  28.      */  
  29.     @RequestMapping(value=“upload.do”,method={RequestMethod.GET,RequestMethod.POST})  
  30.     public  String  uploadExcel(HttpServletRequest request) throws Exception {  
  31.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
  32.         System.out.println(”通过传统方式form表单提交方式导入excel文件!”);  
  33.           
  34.         InputStream in =null;  
  35.         List<List<Object>> listob = null;  
  36.         MultipartFile file = multipartRequest.getFile(”upfile”);  
  37.         if(file.isEmpty()){  
  38.             throw new Exception(“文件不存在!”);  
  39.         }  
  40.         in = file.getInputStream();  
  41.         listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
  42.         in.close();  
  43.           
  44.         //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出  
  45.         for (int i = 0; i < listob.size(); i++) {  
  46.             List<Object> lo = listob.get(i);  
  47.             InfoVo vo = new InfoVo();  
  48.             vo.setCode(String.valueOf(lo.get(0)));  
  49.             vo.setName(String.valueOf(lo.get(1)));  
  50.             vo.setDate(String.valueOf(lo.get(2)));  
  51.             vo.setMoney(String.valueOf(lo.get(3)));  
  52.               
  53.             System.out.println(”打印信息–>机构:”+vo.getCode()+“  名称:”+vo.getName()+“   时间:”+vo.getDate()+“   资产:”+vo.getMoney());  
  54.         }  
  55.         return “result”;  
  56.     }  
  57.       
  58.     /** 
  59.      * 描述:通过 jquery.form.js 插件提供的ajax方式上传文件 
  60.      * @param request 
  61.      * @param response 
  62.      * @throws Exception 
  63.      */  
  64.     @ResponseBody  
  65.     @RequestMapping(value=“ajaxUpload.do”,method={RequestMethod.GET,RequestMethod.POST})  
  66.     public  void  ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {  
  67.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
  68.           
  69.         System.out.println(”通过 jquery.form.js 提供的ajax方式上传文件!”);  
  70.           
  71.         InputStream in =null;  
  72.         List<List<Object>> listob = null;  
  73.         MultipartFile file = multipartRequest.getFile(”upfile”);  
  74.         if(file.isEmpty()){  
  75.             throw new Exception(“文件不存在!”);  
  76.         }  
  77.           
  78.         in = file.getInputStream();  
  79.         listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
  80.           
  81.         //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出  
  82.         for (int i = 0; i < listob.size(); i++) {  
  83.             List<Object> lo = listob.get(i);  
  84.             InfoVo vo = new InfoVo();  
  85.             vo.setCode(String.valueOf(lo.get(0)));  
  86.             vo.setName(String.valueOf(lo.get(1)));  
  87.             vo.setDate(String.valueOf(lo.get(2)));   
  88.             vo.setMoney(String.valueOf(lo.get(3)));  
  89.         }  
  90.           
  91.         PrintWriter out = null;  
  92.         response.setCharacterEncoding(”utf-8”);  //防止ajax接受到的中文信息乱码  
  93.         out = response.getWriter();  
  94.         out.print(”文件导入成功!”);  
  95.         out.flush();  
  96.         out.close();  
  97.     }  
  98.   
  99.   


  • InfoVo.java(保存Excel数据对应的对象)
[java]  view plain  copy
  1. package com.poiexcel.vo;  
  2.   
  3.   
  4. //将Excel每一行数值转换为对象  
  5. public class InfoVo {  
  6.       
  7.     private String code;  
  8.     private String name;  
  9.     private String date;  
  10.     private String money;  
  11.       
  12.     public String getCode() {  
  13.         return code;  
  14.     }  
  15.     public void setCode(String code) {  
  16.         this.code = code;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getDate() {  
  25.         return date;  
  26.     }  
  27.     public void setDate(String date) {  
  28.         this.date = date;  
  29.     }  
  30.     public String getMoney() {  
  31.         return money;  
  32.     }  
  33.     public void setMoney(String money) {  
  34.         this.money = money;  
  35.     }  
  36. }  

  • main.jsp(前端代码):
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
    <%  
    String path = request.getContextPath();  
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
    %>  
    <html>  
      <head>  
        <base href="<%=basePath%>">  
        <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>  
        <script type="text/javascript" src="js/jquery.form.js"></script>   
        <title>My JSP 'index.jsp' starting page</title>  
        <script type="text/javascript">  
                //ajax 方式上传文件操作  
                 $(document).ready(function(){  
                    $('#btn').click(function(){  
                        if(checkData()){  
                            $('#form1').ajaxSubmit({    
                                url:'uploadExcel/ajaxUpload.do',  
                                dataType: 'text',  
                                success: resutlMsg,  
                                error: errorMsg  
                            });   
                            function resutlMsg(msg){  
                                alert(msg);     
                                $("#upfile").val("");  
                            }  
                            function errorMsg(){   
                                alert("导入excel出错!");      
                            }  
                        }  
                    });  
                 });  

                 //JS校验form表单信息  
                 function checkData(){  
                    var fileDir = $("#upfile").val();  
                    var suffix = fileDir.substr(fileDir.lastIndexOf("."));  
                    if("" == fileDir){  
                        alert("选择需要导入的Excel文件!");  
                        return false;  
                    }  
                    if(".xls" != suffix && ".xlsx" != suffix ){  
                        alert("选择Excel格式的文件导入!");  
                        return false;  
                    }  
                    return true;  
                 }  
        </script>   
      </head>  

      <body>  
      <div>1.通过简单的form表单提交方式,进行文件的上</br> 2.通过jquery.form.js插件提供的form表单一步提交功能 </div></br>  
        <form method="POST"  enctype="multipart/form-data" id="form1" action="uploadExcel/upload.do">  
            <table>  
             <tr>  
                <td>上传文件: </td>  
                <td> <input id="upfile" type="file" name="upfile"></td>  
             </tr>  
            <tr>  
                <td><input type="submit" value="提交" onclick="return checkData()"></td>  
                <td><input type="button" value="ajax方式提交" id="btn" name="btn" ></td>  
             </tr>  
            </table>    
        </form>  

      </body>  
    </html>  

  • web.xml:
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="3.0"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">  

      <!-- 加载Spring容器监听 -->  
      <listener>      
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
      </listener>  

      <!-- 设置Spring容器加载配置文件路径 -->  
      <context-param>      
          <param-name>contextConfigLocation</param-name>      
          <param-value>WEB-INF/application/applicationContext-*.xml</param-value>  
      </context-param>  

      <!--配置Springmvc核心控制器-->  
      <servlet>            
            <servlet-name>springmvc</servlet-name>           
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <load-on-startup>1</load-on-startup>  
      </servlet>      
      <!--为DispatcherServlet建立映射 -->        
      <servlet-mapping>    
            <servlet-name>springmvc</servlet-name>        
            <url-pattern>*.do</url-pattern>      
      </servlet-mapping>   
    <welcome-file-list>  
        <welcome-file>main.jsp</welcome-file>  
    </welcome-file-list>    
</web-app>
  • springmvc-servlet.xml(只做简单配置)
[html]  view plain  copy
  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”    
  3.      xmlns:context=“http://www.springframework.org/schema/context”  
  4.      xmlns:mvc=“http://www.springframework.org/schema/mvc”    
  5.      xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”   
  6.      xmlns:tx=“http://www.springframework.org/schema/tx”   
  7.      xsi:schemaLocation=”  
  8.           http://www.springframework.org/schema/beans       
  9.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
  10.           http://www.springframework.org/schema/context  
  11.           http://www.springframework.org/schema/context/spring-context-4.1.xsd  
  12.           http://www.springframework.org/schema/mvc  
  13.           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
  14.           http://www.springframework.org/schema/tx       
  15.           http://www.springframework.org/schema/tx/spring-tx-4.1.xsd     
  16.           http://www.springframework.org/schema/context       
  17.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd ”>  
  18.        
  19.      <!– 启动注解驱动–>    
  20.      <mvc:annotation-driven/>    
  21.      <!– 启动包扫描功能–>    
  22.      <context:component-scan base-package=“com.poiexcel.*” />    
  23.        
  24. </beans>    


  • applicationContext-base.xml
[html]  view plain  copy
  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”    
  3.      xmlns:context=“http://www.springframework.org/schema/context”  
  4.      xmlns:mvc=“http://www.springframework.org/schema/mvc”    
  5.      xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”   
  6.      xmlns:tx=“http://www.springframework.org/schema/tx”   
  7.      xsi:schemaLocation=”  
  8.           http://www.springframework.org/schema/beans       
  9.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
  10.           http://www.springframework.org/schema/context  
  11.           http://www.springframework.org/schema/context/spring-context-4.1.xsd   
  12.           http://www.springframework.org/schema/mvc  
  13.           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
  14.           http://www.springframework.org/schema/tx       
  15.           http://www.springframework.org/schema/tx/spring-tx-4.1.xsd      
  16.           http://www.springframework.org/schema/context       
  17.           http://www.springframework.org/schema/context/spring-context-4.1.xsd ”>  
  18.             
  19.      <!– 视图解释类 –>    
  20.      <bean class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>  
  21.       <property name=“prefix” value=“/WEB-INF/jsp/” />  
  22.       <property name=“suffix” value=“.jsp” />  
  23.      </bean>  
  24.             
  25.     <!– SpringMVC上传文件时,需要配置MultipartResolver处理器 –>  
  26.     <bean id=“multipartResolver” class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”>  
  27.         <property name=“defaultEncoding” value=“utf-8” />  
  28.         <!– 指定所上传文件的总大小不能超过10485760000B。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 –>  
  29.         <property name=“maxUploadSize” value=“10485760000” />  
  30.         <property name=“maxInMemorySize” value=“40960” />  
  31.     </bean>  
  32.             
  33. </beans>            


猜你喜欢

转载自blog.csdn.net/yh869585771/article/details/79904521