java poi 注解,Java之基于poi使用注解更优雅的生成excel文件

通过自定义@ExcelName和@ExcelRow注解,简化了使用Apache POI库创建Excel文件的过程。注解用于标记类和字段,方便地设置Excel的表名和单元格内容。提供了一个名为ReportData的示例类,展示了如何使用这些注解来生成Excel文件。
摘要由CSDN通过智能技术生成

需求

我们经常会遇到需要生成excel文件的需要,这个时候通常会使用apache提供的poi,但原生poi提供的api使用起来比较繁琐,所以我们实现利用注解的方式来快速封装

对象注入

@ExcelName 单页excel的名称 @ExcelRow 每行标题以及位置

@ExcelName("user list")

public class ReportData {

@ExcelRow(headerName = "User Name", columnIndex = 0)

private String username;

@ExcelRow(headerName = "Age", columnIndex = 1)

private int age;

@ExcelRow(headerName = "Sex", columnIndex = 2)

private String sex;

@ExcelRow(headerName = "User Id", columnIndex = 3)

private String userId;

}

复制代码

调用封装方法

在封装的方法中传入对象的class,包含数据的list数组reportData,再输出到一个输出流就完成了

ExcelUtil.newSingleExcel(ReportData.class)

.fillData(reportData)

.flush(outputStream);

复制代码

具体代码实现

定义两个我们需要的注解

@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface ExcelName {

String value() default "";

}

复制代码

@Target({ElementType.FIELD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface ExcelRow {

String headerName() default "";

int columnIndex();

}

复制代码

核心ExcelUtil类

import org.apache.logging.log4j.LogManager;

import org.apache.logging.log4j.Logger;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apach

自己封装的excel导出/导入,可以根据注解来导出excel.本项目一共有13个类,里面还包含了一个反射工具,一个编码工具,10分值了。下面是测试代码 public class Test { public static void main(String[] arg) throws FileNotFoundException, IOException{ testBean(); testMap(); } public static void testBean() throws FileNotFoundException, IOException{ List l = new ArrayList(); for(int i=0;i<100;i++){ l.add(new MyBean()); } //很轻松,只需要二句话就能导出excel BeanExport be = ExportExcel.BeanExport(MyBean.class); be.createBeanSheet("1月份", "1月份人员信息").addData(l); be.createBeanSheet("2月份","2月份人员信息").addData(l); be.writeFile("E:/test/bean人员信息8.xlsx"); } //如果不想用注解,还能根据MAP导出. public static void testMap () throws FileNotFoundException, IOException{ List l = new ArrayList(); l.add(new MapHeader("姓名","name",5000)); l.add(new MapHeader("年龄","age",4000)); l.add(new MapHeader("生日","birthdate",3000)); l.add(new MapHeader("地址","address",5000)); l.add(new MapHeader("双精度","d",4000)); l.add(new MapHeader("float","f",6000)); List<Map> lm = new ArrayList<Map>(); for(int i=0;i<100;i++){ Map map = new HashMap(); map.put("name","闪电球"); map.put("age",100); map.put("birthdate",new Date()); map.put("address","北京市广东省AAA号123楼!"); map.put("d",22.222d); map.put("f",295.22f); lm.add(map); } MapExport me = ExportExcel.mapExport(l); me.createMapSheel("1月份","广东省人员信息").addData(lm); me.createMapSheel("2月份", "北京市人员信息").addData(lm); me.writeFile("E:/test/map人员信息9.xlsx"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值