注解方式 java导出Excel

1.添加自定义注解

package com.study.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 xking
 * @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;
	
	/**
	 * 字段归属组(根据分组导出导入)
	 */
	int[] groups() default {};
}

2.将要导出的数据对象添加自定义注解

package com.study.domin;

import java.io.Serializable;

import com.study.utils.excel.annotation.ExcelField;

public class User implements Serializable{
	
	private static final long serialVersionUID = -2325875742116550611L;

	private Integer id;

    private String username;

    private String password;

    private Integer age;

    
    @ExcelField(title="id",align=2,sort=1)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    
    @ExcelField(title="用户名",align=2,sort=2)
    public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}
	
	@ExcelField(title="密码",align=2,sort=3)
	public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
    
    @ExcelField(title="年龄",align=2,sort=4)
    public Integer getAge() {
        return age;
    }

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

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password="
				+ password + ", age=" + age + "]";
	}
    
    
}

3. 导出集合数据


//输出到浏览器
List<User> users = userService.findAll();
new ExportExcel("测试代码", User.class).setDataList(users).write(response, "用户信息.xlsx").dispose();


4.结果





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值