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

需求

我们经常会遇到需要生成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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值