我们经常需要导入一些列表数据,那怎样用注解去实现呢?
一、新建@Excel注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义导出Excel数据注解
* @author sugar
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* 导出到Excel中时,列的名字.默认值为“未命名”
*/
public String name() default "未命名";
}
二、@Excel的使用
在需要导入或者导入的实体类的字段上标注上@Excel注解,如:
package com.example.springboot4.entity;
import com.example.springboot4.annotation.Excel;
/**
* 三年消耗量
*/
public class ConsumptionEntity {
@Excel(name="物料")
public String material;
@Excel(name="组织")
public String org;
@Excel(name="数量")
public String qty;
@Excel(name="金额")
public String amount;
public ConsumptionEntity() {
}
public ConsumptionEntity(String material, String org, String qty, String amount) {
this.material = material;
this.org = org;
this.qty = qty;
this.amount = amount;
}
@Override
public String toString() {
return "ConsumptionEntity{" +
"material='" + material + '\'' +
", org='" + org + '\'' +
", qty='" + qty + '\'' +
", amount='" + amount + '\'' +
'}';
}
public String getMaterial() {
return material;
}
public void setMaterial(String material) {
this.material = material;
}
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
三、@Excel的解析
咱一步一步来,先写个测试类。
@Test
public void testExcel() {
ConsumptionEntity consumptionEntity=new ConsumptionEntity("钳子","Org-011","100","200.00");
ConsumptionEntity consumptionEntity1=new ConsumptionEntity("剪刀","Org-012","20","200.00");
//模拟查询到的对象集合
List<ConsumptionEntity> list = new ArrayList<>();
list.add(consumptionEntity);
list.add(consumptionEntity1);
//得到ConsumptionEntity对象所有声明的字段
Field[] heads = list.get(0).getClass().getDeclaredFields();
for (Field field : heads){
//查找被Execl注解到的字段
if (field.isAnnotationPresent(Excel.class)){
//得到该字段的注解
Excel attr = field.getAnnotation(Excel.class);
//得到注解的name属性
System.out.print(attr.name()+",");
}
}
System.out.println("");
for (ConsumptionEntity entity : list) {
System.out.print(entity.getMaterial()+",");
System.out.print(entity.getOrg()+",");
System.out.print(entity.getQty()+",");
System.out.print(entity.getAmount());
System.out.println("");
}
}
运行出来的效果
到这里已经成功了一半了。