文档说明参考:http://easypoi.mydoc.io/#text_217704
easy-poi是在传统poi基础上进行了封装和简化,非常易于上手。
一、导入pom
easy-poi依赖apach的commons-collections4
<!--easy-poi-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
<!--common-collections4-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
二、对需要进行导入导出的POJO类进行注解
注解就是@Excel
,可以设置很多值,注意:必须有无参构造函数
@Data
@NoConstucotr
public class Goods {
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 状态:0-无效 1-有效
*/
@Excel(name = "状态", orderNum = "0", width = 10)
private Integer status;
/**
* 商品码code
*/
@Excel(name = "商品code码", orderNum = "1", width = 20)
private String goodCode;
/**
* 商品名称
*/
@Excel(name = "商品名称", orderNum = "3", width = 20)
private String goodName;
}
属性 | 类型 | 默认值 | 说明 |
---|---|---|---|
name | String | null | 列名 |
needMerge | Boolean | false | 纵向合并单元格 |
orderNum | String | “0” | 列的排序,支持name_id |
replace | String[] | {} | 值的替换 导出是{a_id,b_id} 导入反过来 |
savePath | String | “upload” | 导入文件保存路径 |
type | int | 1 | 导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本 |
width | double | 10 | 列宽 |
height | double | 10 | 列高 |
isStatistics | boolean | fasle | 自动统计数据,在追加一行统计,把所有数据都和输出这个处理会吞没异常,请注意这一点 |
isHyperlink | boolean | false | 超链接,如果是需要实现接口返回对象 |
isImportField | boolean | true | 列校验字段,看看这个字段是不是导入的Excel中有,如果没有说明是错误的Excel,读取失败,支持name_id |
exportFormat | String | “” | 导出的时间格式,以这个是否为空来判断是否需要格式化日期 |
importFormat | String | “” | 导入的时间格式,以这个是否为空来判断是否需要格式化日期 |
format | String | “” | 时间格式,相当于同时设置了exportFormat 和 importFormat |
databaseFormat | String | “yyyyMMddHHmmss” | 导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式,用以转换时间格式输出 |
numFormat | String | “” | 数字格式化,参数是Pattern,使用的对象是DecimalFormat |
imageType | int | 1 | 导出类型 1 从file读取 2 是从数据库中读取 默认是文件 同样导入也是一样的 |
suffix | String | “” | 文字后缀,如% 90 变成90% |
isWrap | boolean | true | 是否换行 即支持\n |
mergeRely | int[] | {} | 合并单元格依赖关系,比如第二列合并是基于第一列 则{1}就可以了 |
mergeVertical | boolean | false | 纵向合并内容相同的单元格 |
三、通用工具类
直接copy即可
/**
* EXCEL工具类
*/
@Slf4j
public class ExcelUtil {
/**
* 下载模板文件:需要兼容浏览器
*/
public static void downFile(String path, String filename, HttpServletRequest request,
HttpServletResponse response) {
InputStream fis = null;
OutputStream os = null;
try {
File file = new File(path);// path
String agent = request.getHeader("User-Agent").toUpperCase();
if (agent.contains(SymbolConstants.FIREFOX)) {
filename = new String(filename.getBytes(), StandardCharsets.ISO_8859_1);// firefox浏览器
} else if (agent.contains(SymbolConstants.MSIE)) {
filename = URLEncoder.encode(filename, "UTF-8"