easypoi可以帮助我们把集合对象pojo转换为表格Excel。他是根据反射(动态代理)完成的,详细api参考官方文档:
官方文档
我在开发的时候用的jdk版本是1.8,导入官方3.2.0的jar包,无法导入导出,后来经过百度,改用版本号为3.0.1的jar包才实现了导入导出功能。
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
上述jar包使用3.0.1的版本
后来在晚上找到一个比较使用的工具类,代码粘贴如下
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.lang.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;
/**
* Excel导入导出工具类
*/
public class EasyPoiUtils {
/**
* excel 导出
*
* @param list 数据列表
* @param fileName 导出时的excel名称
* @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 fileName 导出时的excel名称
* @param response
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
//把数据添加到excel表格中
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
}
/**
* excel 导出
*
* @param list 数据列表
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param response
* @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
//把数据添加到excel表格中
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
}
/**
* excel 导出
*
* @param list 数据列表
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @param exportParams 导出参数(标题、sheet名称、是否创建表头,表格类型)
* @param response
*/
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 title 表格内数据标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @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 title 表格内数据标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 导出时的excel名称
* @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 fileName 下载时的文件名称
* @param response
* @param workbook excel数据
*/
private 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 + ".xlsx", "UTF-8"));
workbook.write(response.getOutputStream());
} 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 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 上传的文件
* @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 {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, pojoClass);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
/**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 表格内数据标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, 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);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
}
根据官方文档的提示注解,写好导入导出的实体,省略了set/get方法
public class PublicExcelVO implements Serializable {
@Excel(name = "序号",width = 20,orderNum = "0")
private String id;
@Excel(name = "问题id",width = 27,orderNum = "1")
private String issueId;
@Excel(name = "期数id",width = 20,orderNum = "2")
private Long termId;
@Excel(name = "人",width = 20,orderNum = "3")
private String publishName;
@Excel(name = "问题内容",width = 20,orderNum = "4")
private String descripe;
@Excel(name = "时间",width = 20,orderNum = "5",exportFormat = "yyyy-MM-dd HH:mm:ss", importFormat ="yyyy-MM-dd HH:mm:ss")
private Date createTime;
@Excel(name = "人数",width = 20,orderNum = "6")
private Long count;
@Excel(name = "点赞数",width = 20,orderNum = "7")
private Long replay;
@Excel(name = "评分id",width = 20,orderNum = "8")
private Long scoreId;
@Excel(name = "评分",width = 20,orderNum = "9")
private Double groupScore;
}
在编写业务代码的时候踩到一个坑,由于之前项目有引入下列jar包,会产生jar包冲突,报找不到DocumentFactoryHelper异常,后来删除下列jar包代码成功跑通。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
业务代码参考如下:
@RestController
@RequestMapping("/excel")
@Api(tags = "导入导出")
public class IssuesExcelController {
Logger logger = LoggerFactory.getLogger(IssuesExcelController.class);
@Resource
private IssuesPublishService issuesPublishService;
@Resource
private IssuesScoreMapper issuesScoreMapper;
@GetMapping(value = "/downLoadPublic")
@ApiOperation(value = "导出表")
public CommonResult downLoadPublic(HttpServletRequest request, HttpServletResponse response) {
try {
String title = "导出表"; //标题名
String sheetName = "导出表"; //表名
List<PublicExcelVO> list = issuesPublishService.selectDownLoadPublic();
EasyPoiUtils.exportExcel(list, title, sheetName, PublicExcelVO.class, "downLoad" + System.currentTimeMillis(), response);
} catch (Exception e) {
logger.error("导出失败", e);
}
return new CommonResult(StatusCode.OK,"查询成功","导出成功");
}
/**
* 导入
*/
@PostMapping("/importPublic")
@ApiOperation(value = "导入")
public CommonResult importPublic(@RequestParam("file") MultipartFile file){
List<PublicExcelVO> list = null;
int filed = 0;
int success = 0;
try {
list = EasyPoiUtils.importExcel(file, PublicExcelVO.class);
IssuesScore issuesScore;
Date now=new Date();
for (PublicExcelVO publicExcelVO : list) {
issuesScore = new IssuesScore();
try {
issuesScore.setGroupScore(publicExcelVO.getGroupScore());
if (issuesScoreMapper.selectByPrimaryKey(publicExcelVO.getScoreId())==null){
issuesScore.setCreateDate(now);
issuesScore.setType("pubilsh");
issuesScore.setTypeValue(publicExcelVO.getId());
issuesScore.setIssueId(publicExcelVO.getIssueId());
issuesScoreMapper.insertSelective(issuesScore);
}else {
issuesScore.setId(publicExcelVO.getScoreId());
issuesScore.setUpdateDate(now);
issuesScoreMapper.updateByPrimaryKeySelective(issuesScore);
}
success++;
} catch (Exception e) {
filed++;
logger.error("问题id为"+publicExcelVO.getIssueId()+"的数据导入异常",e);
}
}
logger.info("成功导入数据:" + success + "条 , 失败" + filed + "条");
} catch (Exception e) {
logger.error("数据导入异常", e);
}
return new CommonResult(StatusCode.OK,"查询成功","导入成功");
}
}
用此方法在本地跑是完全没有问题的,单只在此时环境就会包空指针异常,经过排查,可以看到他源码默认是设置了保存文件的,但是springboot项目在打成jar包之后目录结构会发生变化,再去按照之前的路径去找文件会报空指针。
我们舍弃它冗余的方法调用,直接写一个调用底层源码的方法,并且把保存文件改成false,不保存文件,如下:
/**
* excel 导入
*
* @param inputStream 文件输入流
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel2(InputStream inputStream, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
params.setSaveUrl("/excel/");
//是否保存文件
params.setNeedSave(false);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
logger.error("异常信息打印{}",e);
throw new IOException("excel文件不能为空");
} catch (Exception e) {
logger.error("异常信息打印{}",e);
throw new IOException(e.getMessage());
}
}