您的位置:首页 > 编程语言 > Java开发

java导入导出excel 01

2016-05-19 10:52 453 查看


介绍:

对Apache POI 3.9的简单封装,实现Excel的导出导入功能。使用Annotation定义导出导入字段。http://jeesite.com


优点:

简单易用,支持大数量导出,配置简单,代码量少。
支持Excel 2003、2007、2010(xls、xlsx)格式。
支持简单格式设置,对齐方式,排序等
可导出字典类型数据,自定义数据字段类型(例如:部门关联对象,部门名称与部门编号互转)。
无需建立导入模板,系统自动生成。


缺点:

格式单一,无法导出格式比较复杂的表格。
不能使用模板进行导入,导出。


使用示例:

 

1、导出实体对象中的annotation的定义(ExcelField说明见:5、ExcelField定义说明):

  

@Entity  

@Table(name = "sys_user")  

public class User extends BaseEntity {  

  

    private Long id;        // 编号  

    ...  

    ...  

    ...   

    private List<Role> roleList = Lists.newArrayList(); // 拥有角色列表  

      

    @Id  

    @ExcelField(title="ID", type=1, align=2, sort=1)  

    public Long getId() {  

        return id;  

    }  

    @ManyToOne  

    @ExcelField(title="所属区域", align=2, sort=10)  

    public Area getArea() {  

        return area;  

    }  

    @ManyToOne  

    @ExcelField(title="所属部门", align=2, sort=20)  

    public Office getOffice() {  

        return office;  

    }  

    @Length(min=1, max=100)  

    @ExcelField(title="姓名", align=2, sort=40)  

    public String getName() {  

        return name;  

    }  

    @Length(min=0, max=100)  

    @ExcelField(title="用户类型", align=2, sort=80, dictType="sys_user_type")  

    public String getUserType() {  

        return userType;  

    }  

    @ExcelField(title="创建时间", type=0, align=1, sort=90)  

    public Date getCreateDate() {  

        return createDate;  

    }  

    @ExcelField(title="最后登录日期", type=1, align=1, sort=110)  

    public Date getLoginDate() {  

        return loginDate;  

    }  

    @ManyToMany  

    @ExcelField(title="拥有角色", align=1, sort=800, fieldType=RoleListType.class)  

    public List<Role> getRoleList() {  

        return roleList;  

    }  

}  

 

 2、Excel导出示例:

 

public String exportFile(User user) {  

    try {  

        String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";   

                // 查询数据  

        Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);   

                // 1:创建Excel导出对象;2:设置数据;3:写入输出流;4:临时数据销毁  

        new ExportExcel("用户数据", User.class)  

                     .setDataList(page.getList())  

                     .write(response, fileName)  

                     .dispose();  

        return null;  

    } catch (Exception e) {  

        addFlashMessage("导出用户失败!失败信息:"+e.getMessage());  

    }  

    return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";  

}  

 

3、Excel 导入示例:

 

public String importFile(MultipartFile file) {  

    try {  

        int successNum = 0;  

        int failureNum = 0;  

        StringBuilder failureMsg = new StringBuilder();  

                // 创建导入Excel对象  

        ImportExcel ei = new ImportExcel(file, 1, 0);  

                // 获取传入Excel文件的数据,根据传入参数类型,自动转换为对象  

        List<User> list = ei.getDataList(User.class);  

                // 遍历数据,保存数据  

        for (User user : list){  

            try{  

                if ("true".equals(checkLoginName("", user.getLoginName()))){  

                    user.setPassword(SystemService.entryptPassword("123456"));  

                    BeanValidators.validateWithException(validator, user);  

                    systemService.saveUser(user);  

                    successNum++;  

                }else{  

                    failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");  

                    failureNum++;  

                }  

            }catch(ConstraintViolationException ex){  

                failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败:");  

                List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");  

                for (String message : messageList){  

                    failureMsg.append(message+"; ");  

                    failureNum++;  

                }  

            }catch (Exception ex) {  

                failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败:"+ex.getMessage());  

            }  

        }  

        if (failureNum>0){  

            failureMsg.insert(0, ",失败 "+failureNum+" 条用户,导入信息如下:");  

        }  

        addFlashMessage("已成功导入 "+successNum+" 条用户"+failureMsg);  

    } catch (Exception e) {  

        addFlashMessage("导入用户失败!失败信息:"+e.getMessage());  

    }  

    return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";  

}  

 

4、Excel 导入模板下载示例

 

public String importFileTemplate() {  

    try {  

                String fileName = "用户数据导入模板.xlsx";  

        List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser(true));  

                // 第三个参数设置为“2”表示输出为导入模板(1:导出数据;2:导入模板)  

        new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();  

        return null;  

    } catch (Exception e) {  

        addFlashMessage("导出用户失败!失败信息:"+e.getMessage());  

    }  

    return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";  

}  

 

  

5、ExcelField定义说明:

 

 

/** 

 * Copyright © 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. 

 * 

 * Licensed under the Apache License, Version 2.0 (the "License"); 

 */  

package com.thinkgem.jeesite.common.utils.excel.annotation;  

  

import java.lang.annotation.ElementType;  

import java.lang.annotation.Retention;  

import java.lang.annotation.RetentionPolicy;  

import java.lang.annotation.Target;  

  

/** 

 * Excel注解定义 

 * @author ThinkGem 

 * @version 2013-03-10 

 */  

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})  

@Retention(RetentionPolicy.RUNTIME)  

public @interface ExcelField {  

  

    /** 

     * 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”) 

     */  

    String value() default "";  

      

    /** 

     * 导出字段标题 

     */  

    String title();  

      

    /** 

     * 字段类型(0:导出导入;1:仅导出;2:仅导入) 

     */  

    int type() default 0;  

  

    /** 

     * 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右) 

     */  

    int align() default 0;  

      

    /** 

     * 导出字段字段排序(升序) 

     */  

    int sort() default 0;  

  

    /** 

     * 如果是字典类型,请设置字典的type值 

     */  

    String dictType() default "";  

      

    /** 

     * 反射类型 

     */  

    Class<?> fieldType() default Class.class;  

      

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java excel 导入 导出