cn.afterturn
easypoi-spring-boot-starter
4.2.0
package com.geidco.dcp.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 cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
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;
/**
* @author XuPengFei
*/
public class ExcelUtils {
/**
* 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 {
ExportParams params = new ExportParams(title, sheetName, ExcelType.XSSF);
defaultExport(list, pojoClass, fileName, response, params);
}
/**
* 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
public class EmailTaskDetail implements Serializable {
/** 语言版本(zh,en) */
@Excel(name = "语言版本", width = 15, addressList = true, replace = {"中文_zh", "英文_en"})
private String languageType; // 必须
/** 收件人名称 */
@Excel(name = "收件人名称", width = 20)
private String recieveName; // 必须
/** 收件人邮箱 */
// 需要加入此注解
@Excel(name = "收件人邮箱", width = 20)
private String recieveEmail; // 非必须
/** 邮件内容 */
private String emailContent; // 非必须
}
@GetMapping("/downloadTemplate")
@Log("下载模板")
public Result downloadTemplate(HttpServletResponse response) {
try {
// 组装数据
List list = new ArrayList();
ExcelUtils.exportExcel(list, "批量发送邮件信息", "批量发送邮件信息", EmailTaskDetail.class, "批量发送邮件信息", response);
return Result.ok("下载成功!");
} catch (Exception e) {
return Result.error("下载失败!");
}
}
@PostMapping(value = "/importVolunteerData")
@ResponseBody
@Log("志愿者导入")
public Result importVolunteerData(@RequestParam("meetingId") String meetingId, @RequestParam("file") MultipartFile file, HttpServletResponse response) {
if (StringUtils.isEmpty(meetingId)) {
return Result.error("会议id不能为空");
}
Map allOfficeMap = SysUtils.getDictMap("VOL_LANGUAGE_DICT");
HashMap officeMap = new HashMap<>();
for (String key : allOfficeMap.keySet()) {
officeMap.put(allOfficeMap.get(key), key);
}
String officeKey = null;
List list = null;
List failList = null;
ExcelImportResult result = null;
try {
ImportParams importParams = new ImportParams();
importParams.setTitleRows(1);
importParams.setHeadRows(1);
result = ExcelImportUtil.importExcelMore(file.getInputStream(), MeetingVolunteer.class, importParams);
list = result.getList();
failList = result.getFailList();
} catch (Exception e) {
e.printStackTrace();
}
if (CollectionUtils.isNullOrEmpty(list)) {
return Result.error("没有有效的数据,导入数据失败");
}
StringBuilder stringBuilder = new StringBuilder();
String userId = SysUtils.getActiveUser().getUserId().toString();
list.forEach(meetingVolunteer -> {
// 处理自己的业务逻辑
meetingVolunteer.setVolunteerStatus("02");
meetingVolunteer.setMeetingId(meetingId);
meetingVolunteer.setId(idWorker.nextId() + "");
meetingVolunteer.setUpdateBy(userId);
meetingVolunteer.setCreateBy(userId);
// 导入去重
// 导入志愿者手机号
String volunteerMobile = meetingVolunteer.getVolunteerMobile();
List volunteerList = meetingVolunteerService.findVolunteerMobile(volunteerMobile);
if (volunteerList.size() == 0 && StringUtils.isNotBlank(volunteerMobile)) {
meetingVolunteerService.add(meetingVolunteer);
}
if (StringUtils.isBlank(volunteerMobile) || volunteerList.size() != 0) {
stringBuilder.append(meetingVolunteer.getVolunteerName() + ",");
}
});
try {
ExcelUtils.downLoadVolFailExcel(result, response, MeetingVolunteer.class);
} catch (IOException e) {
e.printStackTrace();
}
int length = stringBuilder.length();
return Result.ok(length == 0 ? "导入成功!" : "导入成功!导入志愿者手机号为空的有:" + stringBuilder + ",已跳过");
}
示例图解:
@PostMapping(value = "/importEmailTaskDetailData")
@ResponseBody
@Log("导入邮件信息")
public Result importEmailTaskDetailData(HttpServletRequest request, @RequestParam("file") MultipartFile file, HttpServletResponse response) {
String taskId = request.getParameter("taskId");
if (StringUtils.isEmpty(taskId)) {
return Result.error("任务id不能为空");
}
String officeKey = null;
List list = null;
List failList = null;
ExcelImportResult result = null;
ArrayList headerList = null;
List> mapList = null;
try {
ImportParams params = new ImportParams();
params.setHeadRows(1);
params.setTitleRows(1);
mapList = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
System.out.println(mapList);
} catch (Exception e) {
e.printStackTrace();
}
if (CollectionUtils.isNullOrEmpty(mapList)) {
return Result.error("没有有效的数据,导入数据失败");
}
String userId = SysUtils.getActiveUser().getUserId().toString();
mapList.forEach(map -> {
// 创建实体类对象
EmailTaskDetail detail = new EmailTaskDetail();
String recieveName = "";
String recieveEmail = "";
String content = "";
// 获取key
Set keySet = map.keySet();
System.out.println(keySet);
//邮件内容参数集合
Map parameterMap = new HashMap(100, 100);
for (String str : keySet) {
String value = map.get(str).toString();
if (StringUtils.isNotBlank(value)) {
parameterMap.put("{" + str + "}", value);
}
}
// 获取值
recieveName = (String) map.get("收件人名称");
recieveEmail = (String) map.get("收件人邮箱");
DateTimeFormatter ymdEn = DateTimeFormatter.ofPattern("dd MMM uuuu", Locale.ENGLISH);
String dateEn = LocalDate.now().format(ymdEn);
// 替换模板变量,模板变量示例:{xxxx}
parameterMap.put("{中文日期}", LocalDate.now().toString());
parameterMap.put("{英文日期}", dateEn);
// 我这里区分中英文,中文:zh,英文:en
String language = (String) map.get("语言版本");
EmailTaskTemplate template = emailTaskTemplateService.getObjectByKey(taskId);
if ("中文".equals(language)) {
String contentZh = template.getEmailContentZh();
// 替换之后的内容
content = SysTemplateUtil.getEmailTemplateContent(contentZh, parameterMap);
detail.setLanguageType("zh");// 中文
} else {
String contentEn = template.getEmailContentEn();
// 替换之后的内容
content = SysTemplateUtil.getEmailTemplateContent(contentEn, parameterMap);
detail.setLanguageType("en");// 英文
}
detail.setTemplateId(taskId);
detail.setId(idWorker.nextId() + "");
detail.setIsSend("N");
detail.setCreateBy(userId);
detail.setUpdateBy(userId);
detail.setRecieveEmail(recieveEmail);
detail.setRecieveName(recieveName);
detail.setEmailContent(content);
// 保存导入的数据
emailTaskDetailService.add(detail);
});
return Result.ok("导入成功!");
}