工作项目需要导出Excel功能,发现了EasyPoi。 easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板语言(熟悉的表达式语法),完成复杂的写法。
通过给实体类加注解就能导出Excel。
pom.xm导入依赖
<!-- easypoi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.3.0</version>
</dependency>
工具类
1.新建FileWithExcelUtil.java工具类
package com.zhyx.aggregation.common.utils;
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 lombok.extern.slf4j.Slf4j;
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;
/**
* 导入导出工具类
* @author light
*/
@Slf4j
public class FileWithExcelUtil {
/**
* 导出
*
* @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);
}
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) {
//设置导出样式
exportParams.setStyle(ExcelExportStatisticStyler.class);
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) {
log.error("[monitor][IO][表单功能]", e);
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
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 e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
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 e;
} catch (Exception e) {
e.printStackTrace();
log.error("[monitor][表单功能]", e);
}
return list;
}
}
2.新建ExcelExportStatisticStyler.java工具类
package com.zhyx.aggregation.common.utils;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.ss.usermodel.*;
public class ExcelExportStatisticStyler extends ExcelExportStylerDefaultImpl {
private CellStyle numberCellStyle;
public ExcelExportStatisticStyler(Workbook workbook) {
super(workbook);
createNumberCellStyler();
}
private void createNumberCellStyler() {
numberCellStyle = workbook.createCellStyle();
numberCellStyle.setAlignment(HorizontalAlignment.CENTER);
numberCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
DataFormat dataFormat = workbook.createDataFormat();
//设置导出类型是是数值类型
numberCellStyle.setDataFormat(dataFormat.getFormat("0.00_ "));
numberCellStyle.setWrapText(true);
}
@Override
public CellStyle getStyles(boolean noneStyler, ExcelExportEntity entity) {
//自定义Dict转换
if (entity != null
&& 10==entity.getType()) {
return numberCellStyle;
}
return super.getStyles(noneStyler, entity);
}
}
entity实体类
在实体类上需要导出的字段加 @Excel()注解。
name :导出在Excel中的名称。
width :设置宽度。
orderNum :设置字段导出顺序。
如果需要导出的字段不存在这个实体类,需要在实体类新增字段再加上@TableField(exist = false)注解。
如:
@Excel(name = "活动主题" , width = 30,orderNum = "3")
@TableField(exist = false)
@ApiModelProperty(value = "活动主题")
private String activityTheme;
实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="活动对象", description="")
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
@Excel(name = "活动id" , width = 30,orderNum = "1")
@ApiModelProperty(value = "活动id")
@TableId(value = "activity_id", type = IdType.UUID)
private String activityId;
@Excel(name = "创建人用户id" , width = 30,orderNum = "2")
@ApiModelProperty(value = "创建人用户id")
private String activityCreateUserId;
@Excel(name = "活动主题" , width = 30,orderNum = "3")
@TableField(exist = false)
@ApiModelProperty(value = "活动主题")
private String activityTheme;
@Excel(name = "活动地点" , width = 30,orderNum = "4")
@TableField(exist = false)
@ApiModelProperty(value = "活动地点")
private String activityAddress;
@Excel(name = "活动类型字典" , width = 30,orderNum = "5")
@ApiModelProperty(value = "活动类型字典")
private String activityType;
@Excel(name = "活动状态" , width = 30,orderNum = "6")
@ApiModelProperty(value = "活动状态")
private String activityStatus;
}
Controller层
@ApiResponses({
@ApiResponse(code = 200, message = "成功", response = Activity.class)
})
@ApiOperation(value ="活动参加人员信息列表导出Excel",produces = "application/octet-stream")
@PostMapping(value = "/exportExcel")
public void exportExcel(HttpServletResponse response) {
List<Activity> activityList = activityService.listquery();
FileWithExcelUtil.exportExcel(activityList,"活动参加人员信息列表","sheet页名称",Activity.class,"活动参加人员信息列表.xls",response);
}
produces = “application/octet-stream” 在swagger调试可以变成下载按钮方便调试。
List activityList = activityService.listquery();是查询导出的数据字段。
Service层
public interface ActivityService extends IService<Activity> {
List<Activity> listquery();
}
Service实现类
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {
@Autowired
private ActivityMapper activityMapper;
@Override
public List<Activity> listquery() {
return activityMapper.listquery();
}
}
Mapper 接口
public interface ActivityMapper extends BaseMapper<Activity> {
List<Activity> listquery();
}
Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qianyun.jmtz.mapper.ActivityMapper">
<select id="listquery" parameterType="string" resultMap="BaseResultMap">
SELECT a.activity_id,a.activity_create_user_id,a.activity_theme,activity_content,a.activity_address,
a.activity_type,a.activity_status
FROM activity a
</select>
</mapper>
参考EasyPoi教程:EasyPoi教程