SSM框架+poi实现EXCEL导入

由于本人工作原因,需要在SSM框架里实现excel导入数据库。所以就想记录在博客,有什么问题不要见怪,楼主也是个新手。

一、假如有不会搭建简单SSM框架可以在下面留言,本人会抽出时间再写一篇搭建SSM框架的,所以此处省略。

直接进入正题

一、 ExcelUtils工具类(也就是解析EXCEL文件,判断EXCEL的类型以及数据的类型)
import java.io.IOException;  
import java.io.InputStream;  
import java.math.BigDecimal;

import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.Date;
import java.util.List;  
  
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
import org.apache.poi.ss.usermodel.Workbook;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  
  
public class ExcelUtils {  
      
    private final static String excel2003L =".xls";    //2003- 版本的excel  
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
      
    /** 
     * 描述:获取IO流中的数据,组装成List<List<Object>>对象 
     * @param in,fileName 
     * @return 
     * @throws IOException  
     */  
    public  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
        List<List<Object>> list = null;  
          
        //创建Excel工作薄  
        Workbook work = this.getWorkbook(in,fileName);  
        if(null == work){  
            throw new Exception("创建Excel工作薄为空!");  
        }  
        Sheet sheet = null;  //页数
        Row row = null;  //行数
        Cell cell = null;  //列数
          
        list = new ArrayList<List<Object>>();  
        //遍历Excel中所有的sheet  
        for (int i = 0; i < work.getNumberOfSheets(); i++) {  
            sheet = work.getSheetAt(i);  
            if(sheet==null){continue;}  
              
            //遍历当前sheet中的所有行  
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {  
                row = sheet.getRow(j);  
                if(row==null||row.getFirstCellNum()==j){continue;}  
                  
                //遍历所有的列  
                List<Object> li = new ArrayList<Object>();  
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
                    cell = row.getCell(y);  
                    li.add(this.getValue(cell));  
                }  
                list.add(li);  
            }  
        }  

        return list;  
        
    }  
      
    /** 
     * 描述:根据文件后缀,自适应上传文件的版本  
     * @param inStr,fileName 
     * @return 
     * @throws Exception 
     */  
    public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
        Workbook wb = null;  
        String fileType = fileName.substring(fileName.lastIndexOf("."));  
        if(excel2003L.equals(fileType)){  
            wb = new HSSFWorkbook(inStr);  //2003-  
        }else if(excel2007U.equals(fileType)){  
            wb = new XSSFWorkbook(inStr);  //2007+  
        }else{  
            throw new Exception("解析的文件格式有误!");  
        }  
        return wb;  
    }  
  
    /** 
     * 描述:对表格中数值进行格式化 
     * @param cell 
     * @return 
     */  
  //解决excel类型问题,获得数值  
    public  String getValue(Cell cell) {  
        String value = "";  
        if(null==cell){  
            return value;  
        }  
        switch (cell.getCellType()) {  
        //数值型  
        case Cell.CELL_TYPE_NUMERIC:  
            if (HSSFDateUtil.isCellDateFormatted(cell)) {  
                //如果是date类型则 ,获取该cell的date值  
                Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());  
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
                value = format.format(date);;  
            }else {// 纯数字  
                BigDecimal big=new BigDecimal(cell.getNumericCellValue());  
                value = big.toString();  
                //解决1234.0  去掉后面的.0  
                if(null!=value&&!"".equals(value.trim())){  
                     String[] item = value.split("[.]");  
                     if(1<item.length&&"0".equals(item[1])){  
                         value=item[0];  
                     }  
                }  
            }  
            break;  
            //字符串类型   
        case Cell.CELL_TYPE_STRING:  
            value = cell.getStringCellValue().toString();  
            break;  
        // 公式类型  
        case Cell.CELL_TYPE_FORMULA:  
            //读公式计算值  
            value = String.valueOf(cell.getNumericCellValue());  
            if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串  
                value = cell.getStringCellValue().toString();  
            }  
            break;  
        // 布尔类型  
        case Cell.CELL_TYPE_BOOLEAN:  
            value = " "+ cell.getBooleanCellValue();  
            break;   
        default:  
            value = cell.getStringCellValue().toString();  
    }  
    if("null".endsWith(value.trim())){  
        value="";  
    }  
  return value;  
    }  
      
  
}  

 二、定义两个实体类,一个是对于excel文件,解析它的数据(ExcelBean),另一个是导入数据库表的实体类(people)

ExcelBean.java

import org.apache.poi.xssf.usermodel.XSSFCellStyle;

public class ExcelBean implements java.io.Serializable {  
    private String headTextName;//列头(标题)名  
    private String propertyName;//对应字段名  
    private Integer cols;//合并单元格数  
    private XSSFCellStyle cellStyle;  
      
    public ExcelBean(){  
          
    }  
    public ExcelBean(String headTextName, String propertyName){  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
    }  
      
    public ExcelBean(String headTextName, String propertyName, Integer cols) {  
        super();  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
        this.cols = cols;  
    }   
      
    public String getHeadTextName() {  
       return headTextName;  
   }  
 
   public void setHeadTextName(String headTextName) {  
       this.headTextName = headTextName;  
   }  
 
   public String getPropertyName() {  
       return propertyName;  
   }  
 
   public void setPropertyName(String propertyName) {  
       this.propertyName = propertyName;  
   }  
 
   public Integer getCols() {  
       return cols;  
   }  
 
   public void setCols(Integer cols) {  
       this.cols = cols;  
   }  
 
   public XSSFCellStyle getCellStyle() {  
       return cellStyle;  
   }  
 
   public void setCellStyle(XSSFCellStyle cellStyle) {  
       this.cellStyle = cellStyle;  
   }  
}  

people.java

import java.util.Date;

public class people {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    private Date date;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

三、定义mapper文件(SSM里面就是这种结构,相当于DAO文件一样)。


peopleMapper.java
import com.cn.liebin.entity.people;

public interface peopleMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(people record);

    int insertSelective(people record);

    people selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(people record);

    int updateByPrimaryKey(people record);
}
peopleMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>                                                                                              
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >                         
<mapper namespace="com.cn.liebin.mapping.peopleMapper" >                                                                             
  <resultMap id="BaseResultMap" type="com.cn.liebin.entity.people" >                                                                 
    <id column="id" property="id" jdbcType="INTEGER" />                                                                              
    <result column="user_name" property="userName" jdbcType="VARCHAR" />                                                             
    <result column="password" property="password" jdbcType="VARCHAR" />                                                              
    <result column="age" property="age" jdbcType="INTEGER" />                                                                        
    <result column="date" property="date" jdbcType="DATE" />                                                                         
  </resultMap>                                                                                                                       
  <sql id="Base_Column_List" >                                                                                                       
    id, user_name, password, age, date                                                                                               
  </sql>                                                                                                                             
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >                                      
    select                                                                                                                           
    <include refid="Base_Column_List" />                                                                                             
    from people                                                                                                                      
    where id = #{id,jdbcType=INTEGER}                                                                                                
  </select>                                                                                                                          
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >                                                                
    delete from people                                                                                                               
    where id = #{id,jdbcType=INTEGER}                                                                                                
  </delete>                                                                                                                          
  <insert id="insert" parameterType="com.cn.liebin.entity.people" >                                                                  
    insert into people (id, user_name, password,                                                                                     
      age, date)                                                                                                                     
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},                                      
      #{age,jdbcType=INTEGER}, #{date,jdbcType=DATE})                                                                                
  </insert>                                                                                                                          
  <insert id="insertSelective" parameterType="com.cn.liebin.entity.people" >                                                         
    insert into people                                                                                                               
    <trim prefix="(" suffix=")" suffixOverrides="," >                                                                                
      <if test="id != null" >                                                                                                        
        id,                                                                                                                          
      </if>                                                                                                                          
      <if test="userName != null" >                                                                                                  
        user_name,                                                                                                                   
      </if>                                                                                                                          
      <if test="password != null" >                                                                                                  
        password,                                                                                                                    
      </if>                                                                                                                          
      <if test="age != null" >                                                                                                       
        age,                                                                                                                         
      </if>                                                                                                                          
      <if test="date != null" >                                                                                                      
        date,                                                                                                                        
      </if>                                                                                                                          
    </trim>                                                                                                                          
    <trim prefix="values (" suffix=")" suffixOverrides="," >                                                                         
      <if test="id != null" >                                                                                                        
        #{id,jdbcType=INTEGER},                                                                                                      
      </if>                                                                                                                          
      <if test="userName != null" >                                                                                                  
        #{userName,jdbcType=VARCHAR},                                                                                                
      </if>                                                                                                                          
      <if test="password != null" >                                                                                                  
        #{password,jdbcType=VARCHAR},                                                                                                
      </if>                                                                                                                          
      <if test="age != null" >                                                                                                       
        #{age,jdbcType=INTEGER},                                                                                                     
      </if>                                                                                                                          
      <if test="date != null" >                                                                                                      
        #{date,jdbcType=DATE},                                                                                                       
      </if>                                                                                                                          
    </trim>                                                                                                                          
  </insert>                                                                                                                          
  <update id="updateByPrimaryKeySelective" parameterType="com.cn.liebin.entity.people" >                                             
    update people                                                                                                                    
    <set >                                                                                                                           
      <if test="userName != null" >                                                                                                  
        user_name = #{userName,jdbcType=VARCHAR},                                                                                    
      </if>                                                                                                                          
      <if test="password != null" >                                                                                                  
        password = #{password,jdbcType=VARCHAR},                                                                                     
      </if>                                                                                                                          
      <if test="age != null" >                                                                                                       
        age = #{age,jdbcType=INTEGER},                                                                                               
      </if>                                                                                                                          
      <if test="date != null" >                                                                                                      
        date = #{date,jdbcType=DATE},                                                                                                
      </if>                                                                                                                          
    </set>                                                                                                                           
    where id = #{id,jdbcType=INTEGER}                                                                                                
  </update>                                                                                                                          
  <update id="updateByPrimaryKey" parameterType="com.cn.liebin.entity.people" >                                                      
    update people                                                                                                                    
    set user_name = #{userName,jdbcType=VARCHAR},                                                                                    
      password = #{password,jdbcType=VARCHAR},                                                                                       
      age = #{age,jdbcType=INTEGER},                                                                                                 
      date = #{date,jdbcType=DATE}                                                                                                   
    where id = #{id,jdbcType=INTEGER}                                                                                                
  </update>                                                                                                                          
</mapper>                                                                                                                            

四、定义Service文件

PeopleService.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public interface PeopleService {
	String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response);
}
五、实现Service接口
PeopleServiceImpl.java
import java.io.IOException;

import java.io.InputStream;

import java.sql.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cn.liebin.entity.people;
import com.cn.liebin.service.PeopleService;
import com.cn.liebin.unit.ExcelUtils;
import com.cn.liebin.mapping.peopleMapper;

@Service("PeopleService")
public class PeopleServiceImpl implements PeopleService{
	
	@Resource(name="peopleMapper")
	private  peopleMapper peopleMapper;
	
	public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
        
        MultipartFile file = multipartRequest.getFile("upfile");  
        if(file.isEmpty()){  
            try {
				throw new Exception("文件不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}  
        }  
          
        InputStream in =null;  
        try {
			in = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}  
        
		List<List<Object>> listob = null; 
		try {
			listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}   
		
	    //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出  
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i);  
            people vo = new people(); 
            people j = null;
        	
			try {
				j = peopleMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				System.out.println("没有新增");
			}
			    vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));  
	            vo.setUserName(String.valueOf(lo.get(1)));  
	            vo.setPassword(String.valueOf(lo.get(2)));   
	            vo.setAge(Integer.valueOf(String.valueOf(lo.get(3))));  
	            vo.setDate(Date.valueOf(String.valueOf(lo.get(4)))); 
			if(j == null)
			{
		            peopleMapper.insert(vo);
			}
			else
			{
		            peopleMapper.updateByPrimaryKey(vo);
			}
        }   
        return "文件导入成功!";
	}
}
六、定义Controller来实现调用了。
ExcelController.java
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import com.cn.liebin.service.PeopleService;

@Controller  
@RequestMapping("/uploadExcel/*")    
public class ExcelController {  
    
	 @Resource(name="PeopleService")
     private PeopleService PeopleService;
	  
    /** 
     * 描述:通过 jquery.form.js 插件提供的ajax方式上传文件 
     * @param request 
     * @param response 
     * @throws Exception 
     */  
    @ResponseBody  
    @RequestMapping(value="ajaxUpload.do",method={RequestMethod.GET,RequestMethod.POST})  
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {  
        return PeopleService.ajaxUploadExcel(request, response);
    }  
}  

七、我随便写了一个JSP文件去实现。
excel.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="提交" οnclick="checkData()"></td>  
            <td><input type="button" value="ajax方式提交" id="btn" name="btn" ></td>  
         </tr>  
        </table>    
    </form>  
      
  </body>  

八,实现图片:
前台界面:


Excel文件:

上传文件后导入:

数据库界面:



总结:我的这个Excel导入数据库和其他的不一样,它可以进行数据库的更新覆盖。也就是说假如数据库已经存在过一些数据,而你相对这些数据进行更新,是完全可以实现的。要是没有数据存在过,也可以直接导入数据库。谢谢。



  • 10
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 42
    评论
评论 42
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值