SSM框架poi实现Excel导入(比较详细)

      第一次撸项目,使用SSM框架,需要用Excel导入学生信息,花了很长的时间,特此记录下来,分享给大家,有什么问题希望不要见怪,本人是刚入门的小白。

一、pojo下定义两个实体类,一个是对于excel文件,解析它的数据(ExcelBean),另一个是导入数据库表的实体类(student)
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;  
   }  
}  

student.java

public class Student {
    //用户id
    private Long id;
    //用户登录名
    private String username;
    //用户密码
    private String password;
    private String classname;
    private  String num;

    public Long getId(String stringCellValue) {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public String getNum() {
        return num;
    }

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

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

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }
}

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

public interface StudentMapper {
    Student login(String username);
    int deleteByPrimaryKey(Long id);
     int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(Long id);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
    void insertInfoBatch(List<Student> list);
}

StudentMapper.xml

<mapper namespace="cn.ds.mapper.StudentMapper">


    <resultMap type="cn.ds.pojo.Student" id="BaseResultMap">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="classname" property="classname"  />
        <result column="num" property="num"  />
    </resultMap>
    <sql id="Base_Column_List" >
      id, username, password,classname,num
  </sql>
    <!-- 用户登录的方法 id与方法名中相同  持久层-->
    <select id="login" parameterType="cn.ds.pojo.Student" resultType="Student">
        select * from student where username = #{username}
    </select>
    <insert id="insertInfoBatch" parameterType="java.util.List">
        insert into student (id, username, password,classname,num)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{id,jdbcType=INT},
            #{userName,jdbcType=VARCHAR},
            #{password,jdbcType=VARCHAR} ,
            #{classname,jdbcType=VARCHAR},
            #{num,jdbcType=VARCHAR})
        </foreach>
    </insert>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Long"  >
        select *from student
        where id = #{id}
    </select>
    <insert id="insert" parameterType="cn.ds.pojo.Student" >
    insert into Student (id, username, password,classname,num)
    values (#{id}, #{username}, #{password},
            #{classname}, #{num})
  </insert>
    <update id="updateByPrimaryKey" parameterType="cn.ds.pojo.Student" >
    update student
    set username = #{username},
      password = #{password},
            classname = #{classname},
      num = #{num}
    where id = #{id}
  </update>
</mapper>

三、util下ExcelUtils工具类(也就是解析EXCEL文件,判断EXCEL的类型以及数据的类型)

public class ExcelUtils {

private final static Stringexcel2003L =".xls";    //2003- 版本的excel

    private final static Stringexcel2007U =".xlsx";  //2007+ 版本的excel

    /**

    * 描述:获取IO流中的数据,组装成List<List<Object>>对象

    * @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  WorkbookgetWorkbook(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  StringgetValue(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

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;

    }

}

四、实现service接口
StudentServiceImpl.java

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentmapper;
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("file");

        System.out.println("得到数据文件");
        if(file.isEmpty()){
            try {
                throw new Exception("文件不存在!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in =null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("加载流");
        List<List<Object>> listob = null;
        try {
            System.out.println("加载流");
            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);
            System.out.println("遍历" + listob.get(i));
            Student vo = new Student();
            Student j = null;

            try {
                //j = studentmapper.selectByPrimaryKey(Long.valueOf());
                j = studentmapper.selectByPrimaryKey(Long.valueOf(String.valueOf(lo.get(0))));
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                System.out.println("没有新增");
            }

            vo.setId(Long.valueOf(String.valueOf(lo.get(0))));
            vo.setUsername(String.valueOf(lo.get(1)));
            vo.setPassword(String.valueOf(lo.get(2)));
            vo.setClassname(String.valueOf(lo.get(3)));
            vo.setNum(String.valueOf(lo.get(4)));
            if(j == null)
            {
                studentmapper.insert(vo);
            }
            else
            {
                studentmapper.updateByPrimaryKey(vo);
            }
        }
        return "success";
    }
}

五、控制层Controller
StudentController.java

@ResponseBody
    @RequestMapping(value="ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("这是请求");
         return studentService.ajaxUploadExcel(request, response);
    }

六、jsp页面

<form action="<%=basePath%>/student/ajaxUpload.do" method="post" enctype="multipart/form-data">
    请选择Excel:<input type="file" name="file">
    <input type="submit" name="提交">
</form>

七、实现图片

猜你喜欢

转载自blog.csdn.net/xiaomingds/article/details/84205576