easypoi的介绍
easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员
就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板
语言(熟悉的表达式语法),完成以前复杂的写法
EasyPOi官网
-
GitHub地址:GitHub - liurenjin/easypoi
-
教程地址:EasyPoi教程_V1.0
使用EasyPOI
环境搭建
1.引入相关依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.3</version>
</dependency>
<!--注意:word中要使用循环等标签必须单独导入以下依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
poi相关依赖注解说明
easypoi起因就是Excel的导入导出,最初的模板是实体和Excel的对应,model--row,filed--col 这样利用注解我们可以和容易做到excel到导入导出 经过一段时间发展,现在注解有5个类分别是
- @Excel 作用到filed上面,是对Excel一列的一个描述
- @ExcelCollection 表示一个集合,主要针对一对多的导出,比如一个老师对应多个科目,科目就可以用集合表示
- @ExcelEntity 表示一个继续深入导出的实体,但他没有太多的实际意义,只是告诉系统这个对象里面同样有导出的字段
- @ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出
- @ExcelTarget 这个是作用于最外层的对象,描述这个对象的id,以便支持一个对象可以针对不同导出做出不同处理
注解中的ID的用法 这个ID算是一个比较独特的例子,比如
@ExcelTarget("teacherEntity")
public class TeacherEntity implements java.io.Serializable {
/** name */
@Excel(name = "主讲老师_teacherEntity,代课老师_absent", orderNum = "1", mergeVertical = true,needMerge=true,isImportField = "true_major,true_absent")
private String name;
这里的@ExcelTarget 表示使用teacherEntity这个对象是可以针对不同字段做不同处理 同样的ExcelEntity 和ExcelCollection 都支持这种方式 当导出这对象时,name这一列对应的是主讲老师,而不是代课老师还有很多字段都支持这种做法
@Excel
这个是必须使用的注解,如果需求简单只使用这一个注解也是可以的,涵盖了常用的Excel需求,需要大家熟悉这个功能,主要分为基础,图片处理,时间处理,合并处理几块,name_id是上面讲的id用法,这里就不累言了
属性 | 类型 | 默认值 | 功能 |
---|---|---|---|
name | String | null | 列名,支持name_id |
needMerge | boolean | fasle | 是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row) |
orderNum | String | "0" | 列的排序,支持name_id |
replace | String[] | {} | 值得替换 导出是{a_id,b_id} 导入反过来 |
savePath | String | "upload" | 导入文件保存路径,如果是图片可以填写,默认是upload/className/ IconEntity这个类对应的就是upload/Icon/ |
type | int | 1 | 导出类型 1 是文本 2 是图片,3 是函数,10 是数字 默认是文本 |
width | double | 10 | 列宽 |
height | double | 10 | 列高,后期打算统一使用@ExcelTarget的height,这个会被废弃,注意 |
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[] | {} | 合并单元格依赖关系,比如第二列合并是基于第一列 则{0}就可以了 |
mergeVertical | boolean | fasle | 纵向合并内容相同的单元格 |
fixedIndex | int | -1 | 对应excel的列,忽略名字 |
isColumnHidden | boolean | false | 导出隐藏列 |
@ExcelTarget
限定一个到处实体的注解,以及一些通用设置,作用于最外面的实体
属性 | 类型 | 默认值 | 功能 |
---|---|---|---|
value | String | null | 定义ID |
height | double | 10 | 设置行高 |
fontSize | short | 11 | 设置文字大小 |
@ExcelEntity
标记是不是导出excel 标记为实体类,一遍是一个内部属性类,标记是否继续穿透,可以自定义内部id
属性 | 类型 | 默认值 | 功能 |
---|---|---|---|
id | String | null | 定义ID |
@ExcelCollection
一对多的集合注解,用以标记集合是否被数据以及集合的整体排序
属性 | 类型 | 默认值 | 功能 |
---|---|---|---|
id | String | null | 定义ID |
name | String | null | 定义集合列名,支持nanm_id |
orderNum | int | 0 | 排序,支持name_id |
type | Class<?> | ArrayList.class | 导入时创建对象使用 |
@ExcelIgnore
忽略这个属性,多使用需循环引用中
实体类的使用
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import com.yongyuankuaile.power.common.domain.Query;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 用户管理
*
* @author zyy
* @email zyy@163.com
* @date 2022-08-15 11:27:11
*/
@Data
@TableName("sys_user")
@ExcelTarget("sys_user")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 编号
*/
@TableId
@ApiModelProperty(value = "编号")
@Excel(name = "编号",orderNum = "1")
private Long id;
/**
* 用户名
*/
@Excel(name = "用户名",orderNum = "2")
@ApiModelProperty(value = "用户名")
private String name;
/**
* 密码
*/
@ApiModelProperty(value = "密码")
private String password;
/**
* 盐
*/
@ApiModelProperty(value = "盐")
private String salt;
/**
* 邮箱
*/
@Excel(name = "邮箱",orderNum = "4")
@ApiModelProperty(value = "邮箱")
private String email;
/**
* 手机号
*/
@Excel(name = "手机号",orderNum = "3")
@ApiModelProperty(value = "手机号")
private String mobile;
/**
* 状态 0:禁用 1:正常
*/
@Excel(name = "状态", replace = { "禁用_0", "正常_1" })
@ApiModelProperty(value = "状态 0:禁用 1:正常")
private Integer status;
/**
* 机构ID
*/
@ApiModelProperty(value = "机构ID")
private Long deptId;
/**
* 创建人
*/
@ApiModelProperty(value = "创建人")
private String createBy;
/**
* 创建时间
*/
@Excel(name = "创建时间", format = "yyyy-MM-dd")
@ApiModelProperty(value = "创建时间")
private Date createTime;
/**
* 更新人
*/
@ApiModelProperty(value = "更新人")
private String lastUpdateBy;
/**
* 更新时间
*/
@ApiModelProperty(value = "更新时间")
private Date lastUpdateTime;
/**
* 是否删除 -1:已删除 0:正常
*/
@ApiModelProperty(value = "是否删除 -1:已删除 0:正常")
private Integer delFlag;
@TableField(exist = false)
private String deptName;
}
工具类
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
public class ExcelCommon {
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null) ;
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
编写导入导出测试接口
package com.chenqi.springboot.controller;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.chenqi.springboot.entity.User;
import com.chenqi.springboot.service.UserService;
import com.chenqi.springboot.util.ExcelUtils;
/**
*
* @ClassName: UserController
* @Description: 测试
* @author chenqi
* @date 2018年11月17日
*
*/
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/export")
public void download(HttpServletResponse httpResponse) {
ExcelCommon.exportExcel(userService.list(null),
"用户数据列表" , "用户数据列表",UserEntity.class,"用户数据表.xls",
httpResponse);
}
@GetMapping("/template")
public void template(HttpServletResponse httpResponse) {
ExcelCommon.exportExcel(new ArrayList<>(1),
"设备列表" , "设备列表",UserEntity.class,"用户数据表.xls",
httpResponse);
}
@PostMapping("/import")
public R importExcel(@RequestParam("file") MultipartFile file){
List<UserEntity> resourceDeviceEntities = ExcelCommon.importExcel(file, 1, 1, UserEntity.class);
userService.saveBatch(resourceDeviceEntities);
return R.ok(resourceDeviceEntities.size());
}
}
简单模块的导入导出
工具类
public class FileUtil {
/**
* @Author: ....
* @Description: 将集合数据导出
* @param fileName 导出的文件名称
* @param beanType 导出时集合中的item的Class类型
* @param list 导出用的集合数据
* @Date: 2021-06-16 14:14
*/
public static <T> void exportList(HttpServletResponse response, String fileName, Class<T> beanType, List<T> list) {
if (list == null) {
list = new ArrayList<>();
}
if (StringUtils.isBlank(fileName)) {
fileName = DateTime.now().toString("yyyyMMddHHmmss") + "导出文件.xls";
} else {
if (!fileName.endsWith(".xls")) {
fileName = fileName.trim() + ".xls";
}
}
exportExcel(list, beanType, fileName, response);
}
private static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response) {
ExportParams exportParams = new ExportParams();
exportParams.setCreateHeadRows(true);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
if (workbook != null) {
;
}
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new ExcelImportException(e.getMessage());
}
}
}
Controller
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.json.JSONUtil;
import com.yongyuankuaile.power.common.domain.R;
import com.yongyuankuaile.power.common.poi.utils.ExcelCommon;
import com.yongyuankuaile.power.common.poi.utils.FileUtil;
import com.yongyuankuaile.power.system.entity.UserEntity;
import com.yongyuankuaile.power.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* Excel 导入导出
*
* @author: Tellsea
* @date: 2019/09/04
*/
@Api(tags = "Excel 导入导出")
@Slf4j
@Controller
@RequestMapping("excel")
public class EasyPoiExcelController {
@Autowired
UserService userService;
@PostMapping("/export")
public void export(HttpServletResponse response) {
List<UserEntity> list = new ArrayList<>();
List<UserEntity> list1 = userService.list();
//数据信息
FileUtil.exportList(response,"名称.xls",UserEntity.class,list1);
}
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
ImportParams params = new ImportParams();
List<UserEntity> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
UserEntity.class, params);
userService.saveBatch(result);
System.out.println(JSONUtil.toJsonStr(result));
}
}