SSM框架+poi实现EXCEL导入

功能是用户excel表导入。

导入思想:先把相关的excel表以文件的形式传至后台,后台接受MultipartFile转成流的形式,然后通过ExcelUtils获得相关字段封装成实体,通过for循环添加到数据库。

第一步:导入相关jar

  jar的版本建议用3.17,其他版本可能出现问题。

        
        
            org.apache.poi
            poi
            3.17
            jar
        
         
            org.apache.poi
            poi-ooxml
            3.17
            jar
        

第二步:建工具类ExcelUtils

  该工具类集合了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>对象 
     * @param in,fileName 
     * @return 
     * @throws IOException  
     */  
    public  List> getBankListByExcel(InputStream in,String fileName) throws Exception{  
        List> 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>();  
        //遍历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 li = new ArrayList();  
                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 
  

第三步:编写导入功能controler

作用是接受传过来的excel表。

@RequestMapping(value ="/saveMore", method = RequestMethod.POST)
    @ResponseBody   
	public  JsonResult saveMore(@RequestParam("file") MultipartFile file) throws Exception{
		JsonResult result = null;
		if(file != null){
			result = userService.saveMore(file);	
        }
		return result;	
	}

第四步:编写实体类user

public class User {
    private String id;

    private String code;

    private String password;

    private String name;

    private Integer status;

    private String synopsis;

    private Integer num;

    private Date created;

    private Date updated;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    public String getPassword() {
        return password;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getSynopsis() {
        return synopsis;
    }

    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis == null ? null : synopsis.trim();
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}

 第五步:编写服务处理方法

public JsonResult saveMore(MultipartFile file) { 
        if(file.isEmpty()){  
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                e.printStackTrace();
                return formatErrorResult("500", "文件不存在");
            }  
        }  
        InputStream in =null;  
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return formatErrorResult("500", "输入流异常");
        }  

        List> listob = null; 
        try {
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
            return formatErrorResult("500", "工具类打开异常");
        }   
    
        for (int i = 0; i < listob.size(); i++) {  
            List lo = listob.get(i);  
            User vo = new User(); 
            List j = null;
            try {
            	UserExample example = new UserExample();
            	Criteria criteria = example.createCriteria();
            	criteria.andCodeEqualTo(String.valueOf(lo.get(2)));
                j = userMapper.selectByExample(example);
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                System.out.println("数据库中无该条数据,新增");

            }
            vo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            vo.setName(String.valueOf(lo.get(1)));
            vo.setCode(String.valueOf(lo.get(2)));
            vo.setPassword(String.valueOf(lo.get(3)));
            vo.setStatus(Integer.valueOf(String.valueOf(lo.get(4))));
            vo.setCreated(new Date());
            vo.setUpdated(new Date());
            vo.setNum(0);
            vo.setSynopsis("读书点亮生活!");
            if(j.size() == 0)
            {
               userMapper.insert(vo);
            }
        }   
        return formatSuccessResult("200", "导入成功");
       
    } 
  

第七步:编写jsp传excel表

通过ajax方式上传

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




用户导入






您的位置:用户  >  用户导入
正在上传中!
等待更美好!
心情更舒畅!

效果图如下:

SSM框架+poi实现EXCEL导入_第1张图片

你可能感兴趣的:(ssm框架)