Springboot采用EasyPoi采用前后端分离快速实现Excel导出功能
程序员文章站
2022-03-01 19:49:51
...
实现思路
- 封装excel的工具类,采用EasyPoi,简单,快速;
- 编写PO对象,采用@Excel注解增加注释;
- 查询数据,并将数据封闭至PO对象中;
- 通过工具类将对象通过BLOB格式返回给前端;
- 前端通过工具类下载该EXCEL;
引依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.2.0</version>
</dependency>
写工具类ExcelUtil
package vip.mate.core.web.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.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* Excel导入导出工具类
* @author pangu
*/
public class ExcelUtil {
/**
* 导出工具类
* @param list
* @param title
* @param sheetName
* @param pojoClass
* @param fileName
* @param isCreateHeader
* @param response
*/
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);
}
/**
* 导出工具类
* @param list
* @param title
* @param sheetName
* @param pojoClass
* @param fileName
* @param response
*/
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);
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 NormalException(e.getMessage());
}
}
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;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
//throw new NormalException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
//throw new NormalException(e.getMessage());
} 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 (NoSuchElementException e){
// throw new NormalException("excel文件不能为空");
} catch (Exception e) {
//throw new NormalException(e.getMessage());
System.out.println(e.getMessage());
}
return list;
}
}
写PO对象(样例SysRolePOI)
package vip.mate.system.poi;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import vip.mate.core.common.constant.MateConstant;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
public class SysRolePOI implements Serializable {
private static final long serialVersionUID = 5758487990585198585L;
@Excel(name = "角色编号" ,orderNum = "0", width = 30, isImportField = "true_st")
private Long id;
@Excel(name = "角色名称" ,orderNum = "1", width = 30, isImportField = "true_st")
private String roleName;
@Excel(name = "角色编码" ,orderNum = "2", width = 30, isImportField = "true_st")
private String roleCode;
@Excel(name = "角色描述" ,orderNum = "3", width = 30, isImportField = "true_st")
private String description;
@Excel(name = "创建时间", format = MateConstant.DATETIME_FORMAT, orderNum = "4", width = 30, isImportField = "true_st")
private LocalDateTime createTime;
}
以上请自行参考样例发挥,如有必要可以参考官方文档
拼数据
这个就不写样例了,就是将这个POI填充上数据即可,不管用什么方法
通过工具类的方法将数据导出成BLOB格式,样例
@GetMapping("/export-role")
@ApiOperation(value = "导出角色列表", notes = "导出角色列表")
public void export(@ApiIgnore HttpServletResponse response) {
List<SysRolePOI> sysRolePOIS = sysRoleService.export();
//使用工具类导出excel
ExcelUtil.exportExcel(sysRolePOIS, null, "角色", SysRolePOI.class, "role", response);
}
就是这样简简单的调用。
前端接受数据
handleExport(){
exportRole().then(response => {
downloadFile(response, "role", 'xlsx')
})
}
以下是downloadFile的方法
// 下载文件
export function downloadFile(obj, name, suffix) {
const url = window.URL.createObjectURL(new Blob([obj]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
至此大功告成
完整代码样例
如果你觉得不过瘾,想看看完整的代码,请进入:
这里有你想要的完整的样例代码。
上一篇: 带头结点双循环链表
下一篇: 当我需要的数据使用的是同一个数据库表时