【开发心得】EasyPoi导入导出的基本使用
网上关于Java导入导出Excel 的文章比较多,相对的坑也比较多(或者因为读者个人水平),特根据自己日常开发中的踩坑,写点东西。
1.常见的Java领域Excel导入导出的类库,基础库(Apache common POI,JExcelAPI,JXL等等...),个人觉得apache的这个可能更好一些,毕竟贡献者多,但是有一个很大的问题,就是每次大版本更新,变动就会很大,博主有一篇文章是阐述从低版本POI升级到高版本的POI可能遇到的问题和解决方案. 基于Apache common POI的二次封装工具有EasyExcel(alibaba),EasyPOI.这两者可谓是各有千秋,各有优劣,虽然网上很多都觉得ali的更为强悍一些,但是出现的时间比easypoi时间要晚,相对来说,恼人的坑还是比较多的(建议多读官网文档或者阅读源码),而easypoi在大批量导出的时候对内存的消耗有点厉害.
2.之前看的比较多的版本都是使用easyPOI低版本进行导入导出的,博主这里使用高版本的easypoi,依赖如下.
<!--apache common poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<!--easypoi-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.0.0</version>
</dependency>
3.工具类:
package com.hmwl.media.modules.ma.util; //换成你自己的包
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.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Created by martin on 2020/3/12 0012 13:50
*/
public class EasyPoiUtil {
/**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param isCreateHeader 是否创建表头
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
}
/**
* excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
* excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, fileName, response);
}
/**
* 默认的 excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
/**
* 默认的 excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
// map中需要添加k
// title 对应表格Title
// key entity 对应表格对应实体
// key data Collection 数据
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
}
/**
* 下载
*
* @param fileName 文件名称
* @param response
* @param workbook excel数据
*/
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param filePath excel文件路径
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedSave(true);
params.setSaveUrl("/excel/");
try {
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("模板不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param file excel文件
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
return importExcel(file, 1, 1, pojoClass);
}
/**
* excel 导入
*
* @param file excel文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
return importExcel(file, titleRows, headerRows, false, pojoClass);
}
/**
* excel 导入
*
* @param file 上传的文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerfiy 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerfiy 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("/excel/");
params.setNeedSave(true);
params.setNeedVerify(needVerfiy);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* Excel 类型枚举
*/
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value;
ExcelTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
4.普通导入
可以选择使用模型注解导入
package [换成自己的包].vo;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import java.io.Serializable;
@Data
public class MenuButtonExcel implements Serializable {
@Excel(name = "primary_id", orderNum = "1", width = 20) //注意这里的name 要和excel的列名完全一致 orderNum是指的第几列,注意从1开始,width是指宽度
private String primary_id;
@Excel(name = "parent_id", orderNum = "2", width = 20)
private String parent_id;
@Excel(name = "parent_ids", orderNum = "3", width = 20)
private String parent_ids;
@Excel(name = "code", orderNum = "4", width = 20)
private String code;
@Excel(name = "name", orderNum = "5", width = 20)
private String name;
@Excel(name = "href", orderNum = "6", width = 20)
private String href;
@Excel(name = "level", orderNum = "6", width = 20)
private String level;
@Excel(name = "type", orderNum = "8", width = 20)
private String type;
@Excel(name = "sequence", orderNum = "9", width = 20)
private String sequence;
@Excel(name = "permission", orderNum = "10", width = 20)
private String permission;
@Excel(name = "is_sys", orderNum = "11", width = 20)
private String is_sys;
@Excel(name = "del_flag", orderNum = "17", width = 20)
private String del_flag;
}
注意这里的name 要和excel的列名完全一致 orderNum是指的第几列,注意从1开始,width是指宽度(如果name对不起来,可能会导致读取出现Null的问题)
5.核心实现代码(service)
String path = null;
try {
path = ResourceUtils.getURL("classpath:").getPath();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<MenuButtonExcel> list = null;
try {
list = EasyPoiUtil.importExcel(path+"权限接入拟定表.xlsx", 0, 1, MenuButtonExcel.class);
} catch (IOException e) {
e.printStackTrace();
}
Integer result = -1;
for (MenuButtonExcel ex:list) {
logger.info(ex.toString());
result = systemSettingMapper.importPermission(ex);
}
6.导出
导出的话,方法也是很多,比如直接通过pojo类导出,或者使用模型导出.
但是要注意的问题有:1.如果想导出忽略某个列使用@ExcelIgnore
模型导出示例代码:
List<ExcelProgram> excelPrograms = null;
try {
excelPrograms = EasyPoiUtil.importExcel(fileUrl,0,1,ExcelProgram.class);
} catch (IOException e) {
e.printStackTrace();
}
List<Map<String,Object>>导出的话,请注意源码.(EasyExportUtil)
public static Workbook exportExcel(List<Map<String, Object>> list, ExcelType type) {
Workbook workbook = getWorkbook(type, 0);
Iterator var3 = list.iterator();
while(var3.hasNext()) {
Map<String, Object> map = (Map)var3.next();
ExcelExportService service = new ExcelExportService();
service.createSheet(workbook, (ExportParams)map.get("title"), (Class)map.get("entity"), (Collection)map.get("data"));
}
return workbook;
}
有几个key 是需要的 title 对应的标题,entity对应的是实体,data对应的是数据:
public static Workbook exportExcel(TemplateExportParams params, Class<?> pojoClass, Collection<?> dataSet, Map<String, Object> map) {
return (new ExcelExportOfTemplateUtil()).createExcleByTemplate(params, pojoClass, dataSet, map);
}
另外一个方法可以供【动态导出列使用】
public static Workbook exportExcel(TemplateExportParams params, Class<?> pojoClass, Collection<?> dataSet, Map<String, Object> map) { return (new ExcelExportOfTemplateUtil()).createExcleByTemplate(params, pojoClass, dataSet, map); }