一、创建工具类
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.msunsoft.episurwey.dto.Covid19QuestionnaireCommunityExcelDTO;
import com.msunsoft.episurwey.util.EasyExcelListener;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.IndexedColors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author :
* EasyExcel导入导出工具类
* @date :2021/11/25 15:56
*/
public class EasyExcelUtils {
public static void webWriteExcelForCommunityPersonnelInformation(HttpServletResponse response, List objects, Class clazz, List<Map<Integer, String>> errMsgList, String sheetName) throws IOException {
//标题样式
WriteCellStyle headCellStyle = new WriteCellStyle();
headCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//数据样式
WriteCellStyle contentCellStyle = new WriteCellStyle();
contentCellStyle.setWrapped(true);
contentCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));
String fileName = sheetName;
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle);
fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
ServletOutputStream outputStream = response.getOutputStream();
try {
ExcelWriterBuilder write = EasyExcel.write(outputStream, clazz).registerWriteHandler(new CommunityPersonneInformationHandler(sheetName));
if (errMsgList != null) {
//inMemory(Boolean.TRUE)开启批注 批注在ErrorSheetWriteHandler中实现
write.inMemory(Boolean.TRUE)
.registerWriteHandler(new ErrorSheetWriteHandler(errMsgList));
}
write.registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.sheet(sheetName).relativeHeadRowIndex(2).doWrite(objects);
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、创建模板对应实体类
package com.msunsoft.episurwey.dto;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.msunsoft.episurwey.util.easyExcel.ExcelPatternMsg;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.Pattern;
/**
* @author
* @description
* @since 2023/02/27
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@HeadRowHeight(80)
@ColumnWidth(20)
public class CommunityPersonnelSerumInformationExcelDTO {
@ApiModelProperty(name = "questionnaireNumber", value = "问卷编号")
@ExcelProperty(value = "血清编号*", index = 0)
private String questionnaireNumber;
@ApiModelProperty(name = "name", value = "姓名")
@ExcelProperty(value = "姓名*", index = 1)
private String name;
@ApiModelProperty(name = "idCard", value = "身份证号")
@ExcelProperty(value = "身份证号*", index = 2)
@ColumnWidth(35)
private String idCard;
@ApiModelProperty(name = "cardType", value = "证件类型 0身份证、1护照、2港澳台身份证")
@ExcelProperty(value = "证件类型*", index = 3)
private String cardTypeValue;
@ApiModelProperty(name = "phone", value = "手机号")
@ExcelProperty(value = "手机号*", index = 4)
private String phone;
@ApiModelProperty(name = "gender", value = "性别 0 女 1男")
@ExcelProperty(value = "性别", index = 5)
private String genderValue;
@ApiModelProperty(name = "age", value = "年龄")
@ExcelProperty(value = "年龄", index = 6)
private Integer age;
@ApiModelProperty(name = "marryStatus", value = "婚姻状况 0未知 1 未婚 2 已婚 3 离婚/分居 4 丧偶")
@ExcelProperty(value = "婚姻状况", index = 7)
private String marryStatusValue;
@ApiModelProperty(name = "educationDegree", value = "文化程度 0未知 1 文盲半文盲 2 小学 3 初中 4 高中/中专 5 大专 6 本科及以上")
@ExcelProperty(value = "文化程度", index = 8)
private String educationDegreeValue;
@ApiModelProperty(name = "height", value = "身高cm")
@ExcelProperty(value = "身高(cm)", index = 9)
private String height;
@ApiModelProperty(name = "weight", value = "体重(kg)")
@ExcelProperty(value = "体重(kg)", index = 10)
private String weight;
@ApiModelProperty(name = "provinceCode", value = "省编码")
@ExcelProperty(value = "省编码", index = 11)
private String provinceCode;
@ApiModelProperty(name = "cityCode", value = "市编码")
@ExcelProperty(value = "市编码", index = 12)
private String cityCode;
@ApiModelProperty(name = "countyCode", value = "区县编码")
@ExcelProperty(value = "区县编码", index = 13)
private String countyCode;
@ApiModelProperty(name = "streetCode", value = "乡镇/街道编码")
@ExcelProperty(value = "乡镇/街道编码", index = 14)
private String streetCode;
@ApiModelProperty(name = "villageCode", value = "村/居委会编码")
@ExcelIgnore
private String villageCode;
@ApiModelProperty(name = "villageName", value = "村/居委会名称")
@ExcelProperty(value = "村/居委会名称", index = 15)
@ColumnWidth(35)
private String villageName;
@ApiModelProperty(name = "nowAddress", value = "现住址")
@ColumnWidth(35)
@ExcelProperty(value = "现住址", index = 16)
private String nowAddress;
@ApiModelProperty(name = "vaccineNumber", value = "接种了几针新冠疫苗 0,1,2,3,4,5")
@ExcelProperty(value = "新冠疫苗接种情况", index = 17)
private String vaccineNumberValue;
@ApiModelProperty(name = "firstVaccineTime", value = "第1针接种时间(填年月日)")
@ExcelProperty(value = "第1针接种时间", index = 18)
@Pattern(regexp = ExcelPatternMsg.DATE_TIMEFOUR, message = ExcelPatternMsg.DATE_TIMEPNE_MSG)
private String firstVaccineTime;
@ExcelProperty(value = "第1针疫苗种类和生产厂家", index = 19)
@ColumnWidth(35)
private String firstVaccineTypeValue;
@ApiModelProperty(name = "secondVaccineTime", value = "第2针接种时间(填年月日)")
@ExcelProperty(value = "第2针接种时间", index = 20)
@Pattern(regexp = ExcelPatternMsg.DATE_TIMEFOUR, message = ExcelPatternMsg.DATE_TIMEPNE_MSG)
private String secondVaccineTime;
@ExcelProperty(value = "第2针疫苗种类和生产厂家", index = 21)
@ColumnWidth(35)
private String secondVaccineTypeValue;
@ApiModelProperty(name = "thirdVaccineTime", value = "第3针接种时间(填年月日)")
@ExcelProperty(value = "第3针接种时间", index = 22)
@Pattern(regexp = ExcelPatternMsg.DATE_TIMEFOUR, message = ExcelPatternMsg.DATE_TIMEPNE_MSG)
private String thirdVaccineTime;
@ExcelProperty(value = "第3针疫苗种类和生产厂家", index = 23)
@ColumnWidth(35)
private String thirdVaccineTypeValue;
@ApiModelProperty(name = "fourthVaccineTime", value = "第4针接种时间(填年月日)")
@ExcelProperty(value = "第4针接种时间", index = 24)
@Pattern(regexp = ExcelPatternMsg.DATE_TIMEFOUR, message = ExcelPatternMsg.DATE_TIMEPNE_MSG)
private String fourthVaccineTime;
@ExcelProperty(value = "第4针疫苗种类和生产厂家", index = 25)
@ColumnWidth(35)
private String fourthVaccineTypeValue;
@ApiModelProperty(name = "fifthVaccineTime", value = "第5针接种时间(填年月日)")
@ExcelProperty(value = "第5针接种时间", index = 26)
@Pattern(regexp = ExcelPatternMsg.DATE_TIMEFOUR, message = ExcelPatternMsg.DATE_TIMEPNE_MSG)
private String fifthVaccineTime;
@ExcelProperty(value = "第5针疫苗种类和生产厂家", index = 27)
@ColumnWidth(35)
private String fifthVaccineTypeValue;
@ApiModelProperty(name = "firstVaccineOtherType", value = "第1针疫苗种类和生产厂家其他")
@ExcelIgnore
private String firstVaccineOtherType;
@ApiModelProperty(name = "secondVaccineOtherType", value = "第2针疫苗种类和生产厂家其他")
@ExcelIgnore
private String secondVaccineOtherType;
@ApiModelProperty(name = "thirdVaccineOtherType", value = "第3针疫苗种类和生产厂家其他")
@ExcelIgnore
private String thirdVaccineOtherType;
@ApiModelProperty(name = "fourthVaccineOtherType", value = "第4针疫苗种类和生产厂家其他")
@ExcelIgnore
private String fourthVaccineOtherType;
@ApiModelProperty(name = "fifthVaccineOtherType", value = "第5针疫苗种类和生产厂家其他")
@ExcelIgnore
private String fifthVaccineOtherType;
@ExcelIgnore
private String createUserId;
}
三、创建模板样式
package com.msunsoft.episurwey.util.easyExcel;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.msunsoft.episurwey.common.CommunityPersonnelInformationEnum;
import com.msunsoft.episurwey.common.TemplateTitleConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import java.util.*;
/**
* @author
* @description
* @since 2023/02/17
*/
public class CommunityPersonnelInformationHandler implements SheetWriteHandler {
private final String title;
public CommunityPersonnelInformationHandler(String title) {
this.title = title;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Workbook workbook = writeWorkbookHolder.getWorkbook();
Sheet sheet = workbook.getSheetAt(0);
//设置标题
Row row1 = sheet.createRow(0);
row1.setHeight((short) 600);
Cell cell1 = row1.createCell(5);
cell1.setCellValue(title);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setAlignment(HorizontalAlignment.LEFT);
Font font = workbook.createFont();
font.setBold(true);
font.setFontHeight((short) 400);
cellStyle.setFont(font);
cell1.setCellStyle(cellStyle);
sheet.addMergedRegionUnsafe(new CellRangeAddress(0, 0, 0, 4));
sheet.addMergedRegionUnsafe(new CellRangeAddress(0, 0, 5, 24));
//表头
Row row2 = sheet.createRow(1);
row2.setHeight((short) 2400);
row2.createCell(0).setCellValue(TemplateTitleConstant.REQUIRED);
row2.createCell(1).setCellValue(TemplateTitleConstant.REQUIRED);
row2.createCell(2).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.SCIENTIFIC_NOTATION);
row2.createCell(3).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(4).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.PHONE_TYPE);
row2.createCell(5).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(6).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.NUMBER_TYPE);
row2.createCell(7).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(8).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(11).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.PROVINCE_CODE_FORMAT);
row2.createCell(12).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.CITY_CODE_FORMAT);
row2.createCell(13).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.COUNTY_CODE_FORMAT);
row2.createCell(14).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.STREET_CODE_FORMAT);
row2.createCell(15).setCellValue(TemplateTitleConstant.REQUIRED + "\n" + TemplateTitleConstant.VILLAGE_NAME_FORMAT);
row2.createCell(17).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(18).setCellValue(TemplateTitleConstant.DATE_TIME_FORMART_3);
row2.createCell(19).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(20).setCellValue(TemplateTitleConstant.DATE_TIME_FORMART_3);
row2.createCell(21).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(22).setCellValue(TemplateTitleConstant.DATE_TIME_FORMART_3);
row2.createCell(23).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(24).setCellValue(TemplateTitleConstant.DATE_TIME_FORMART_3);
row2.createCell(25).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
row2.createCell(26).setCellValue(TemplateTitleConstant.DATE_TIME_FORMART_3);
row2.createCell(27).setCellValue(TemplateTitleConstant.DROP_DOWN_BOX);
//设置单元格格式
CellStyle cellStyle1 = workbook.createCellStyle();
Font font1 = workbook.createFont();
font1.setColor((short) 2);
font1.setFontHeight((short) 250);
cellStyle1.setFont(font1);
cellStyle1.setWrapText(true);
row2.getCell(0).setCellStyle(cellStyle1);
row2.getCell(1).setCellStyle(cellStyle1);
row2.getCell(2).setCellStyle(cellStyle1);
row2.getCell(3).setCellStyle(cellStyle1);
row2.getCell(4).setCellStyle(cellStyle1);
row2.getCell(5).setCellStyle(cellStyle1);
row2.getCell(6).setCellStyle(cellStyle1);
row2.getCell(7).setCellStyle(cellStyle1);
row2.getCell(8).setCellStyle(cellStyle1);
row2.getCell(11).setCellStyle(cellStyle1);
row2.getCell(12).setCellStyle(cellStyle1);
row2.getCell(13).setCellStyle(cellStyle1);
row2.getCell(14).setCellStyle(cellStyle1);
row2.getCell(15).setCellStyle(cellStyle1);
row2.getCell(17).setCellStyle(cellStyle1);
row2.getCell(18).setCellStyle(cellStyle1);
row2.getCell(19).setCellStyle(cellStyle1);
row2.getCell(20).setCellStyle(cellStyle1);
row2.getCell(21).setCellStyle(cellStyle1);
row2.getCell(22).setCellStyle(cellStyle1);
row2.getCell(23).setCellStyle(cellStyle1);
row2.getCell(24).setCellStyle(cellStyle1);
row2.getCell(25).setCellStyle(cellStyle1);
row2.getCell(26).setCellStyle(cellStyle1);
row2.getCell(27).setCellStyle(cellStyle1);
row2.setHeight((short) 3200);
List<String> cardType = new ArrayList<>();
List<String> gender = new ArrayList<>();
List<String> marryStatus = new ArrayList<>();
List<String> educationDegree = new ArrayList<>();
List<String> vaccineType = new ArrayList<>();
List<String> vaccineNumber = new ArrayList<>();
//获取下拉框数据
for (CommunityPersonnelInformationEnum value : CommunityPersonnelInformationEnum.values()) {
if (CommunityPersonnelInformationEnum.VACCINE_TYPE_1.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
vaccineType.add(value.getValue());
} else if (CommunityPersonnelInformationEnum.CARD_TYPE_1.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
cardType.add(value.getValue());
} else if (CommunityPersonnelInformationEnum.GENDER_1.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
gender.add(value.getValue());
} else if (CommunityPersonnelInformationEnum.MARRY_STATUS_0.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
marryStatus.add(value.getValue());
} else if (CommunityPersonnelInformationEnum.EDUCATION_DEGREE_0.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
educationDegree.add(value.getValue());
} else if (CommunityPersonnelInformationEnum.VACCINE_NUMBER_0.getType().equals(value.getType()) && StringUtils.isNotBlank(value.getValue())) {
vaccineNumber.add(value.getValue());
}
}
Map<Integer, String[]> mapDropDown = new HashMap<>(16);
mapDropDown.put(3, cardType.toArray(new String[]{}));
mapDropDown.put(5, gender.toArray(new String[]{}));
mapDropDown.put(7, marryStatus.toArray(new String[]{}));
mapDropDown.put(8, educationDegree.toArray(new String[]{}));
mapDropDown.put(17, vaccineNumber.toArray(new String[]{}));
String[] vaccineTypes = vaccineType.toArray(new String[]{});
mapDropDown.put(19, vaccineTypes);
mapDropDown.put(21, vaccineTypes);
mapDropDown.put(23, vaccineTypes);
mapDropDown.put(25, vaccineTypes);
mapDropDown.put(27, vaccineTypes);
//设置下拉框
DataValidationHelper helper = sheet.getDataValidationHelper();
for (Map.Entry<Integer, String[]> entry : mapDropDown.entrySet()) {
//起始行、终止行、起始列、终止列
//获取需要设置下拉框的区域
CellRangeAddressList addressList = new CellRangeAddressList(2, 1000, entry.getKey(), entry.getKey());
//设置下拉框数据
DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
//绑定
DataValidation dataValidation = helper.createValidation(constraint, addressList);
//处理Excel兼容性问题
if (dataValidation instanceof XSSFDataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(dataValidation);
}
}
}
四、设计的枚举
import com.msunsoft.episurwey.util.ConstantUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author Hao
* @description
* @since 2023/02/17
*/
@Getter
@AllArgsConstructor
public enum CommunityPersonnelInformationEnum {
CARD_TYPE_1("cardType", 0, "身份证"),
CARD_TYPE_2("cardType", 1, "护照"),
CARD_TYPE_3("cardType", 2, "港澳台身份证"),
GENDER_1("gender", 0, "女"),
GENDER_2("gender", 1, "男"),
MARRY_STATUS_0("marryStatus", 0, ""),
MARRY_STATUS_1("marryStatus", 1, "未婚"),
MARRY_STATUS_2("marryStatus", 2, "已婚"),
MARRY_STATUS_3("marryStatus", 3, "离婚/分居"),
MARRY_STATUS_4("marryStatus", 4, "丧偶"),
EDUCATION_DEGREE_0("educationDegree", 0, ""),
EDUCATION_DEGREE_1("educationDegree", 1, "文盲半文盲"),
EDUCATION_DEGREE_2("educationDegree", 2, "小学"),
EDUCATION_DEGREE_3("educationDegree", 3, "初中"),
EDUCATION_DEGREE_4("educationDegree", 4, "高中/中专"),
EDUCATION_DEGREE_5("educationDegree", 5, "大专"),
EDUCATION_DEGREE_6("educationDegree", 6, "本科及以上"),
VACCINE_NUMBER_0("vaccineNumber", 0, "未接种"),
VACCINE_NUMBER_1("vaccineNumber", 1, "一针"),
VACCINE_NUMBER_2("vaccineNumber", 2, "两针"),
VACCINE_NUMBER_3("vaccineNumber", 3, "三针"),
VACCINE_NUMBER_4("vaccineNumber", 4, "四针"),
VACCINE_NUMBER_5("vaccineNumber", 5, "五针"),
VACCINE_TYPE_1("VaccineType", 1, "灭活疫苗-国药中生-北京生物"),
VACCINE_TYPE_2("VaccineType", 2, "灭活疫苗-国药中生-武汉生物"),
VACCINE_TYPE_3("VaccineType", 3, "灭活疫苗-北京科兴中维"),
VACCINE_TYPE_4("VaccineType", 4, "灭活疫苗-深圳康泰"),
VACCINE_TYPE_5("VaccineType", 5, "灭活疫苗-医科院生物所"),
VACCINE_TYPE_6("VaccineType", 6, "重组蛋白疫苗-神州细胞"),
VACCINE_TYPE_7("VaccineType", 7, "重组蛋白疫苗-浙江三叶草"),
VACCINE_TYPE_8("VaccineType", 8, "重组蛋白疫苗-安徽智飞"),
VACCINE_TYPE_9("VaccineType", 9, "重组蛋白疫苗-珠海丽珠"),
VACCINE_TYPE_10("VaccineType", 10, "重组蛋白疫苗-成都威斯克"),
VACCINE_TYPE_11("VaccineType", 11, "腺病毒载体疫苗-康希诺(吸入)"),
VACCINE_TYPE_12("VaccineType", 12, "腺病毒载体疫苗-康希诺(肌注)"),
VACCINE_TYPE_13("VaccineType", 13, "mRNA疫苗-辉瑞"),
VACCINE_TYPE_14("VaccineType", 14, "mRNA疫苗-Moderna"),
VACCINE_TYPE_15("VaccineType", 15, "流感病毒鼻喷-北京万泰"),
VACCINE_TYPE_99("VaccineType", 99, "其他");
private final String type;
private final Integer key;
private final String value;
public static String getValueByKey(String type,Integer key) {
for (CommunityPersonnelInformationEnum value : CommunityPersonnelInformationEnum.values()) {
if (value.type.equals(type) && value.getKey().intValue() == key.intValue()) {
return value.value;
}
}
return ConstantUtil.BLANK;
}
public static Integer getKeyByValue(String type, String value) {
for (CommunityPersonnelInformationEnum informationEnum : CommunityPersonnelInformationEnum.values()) {
if (informationEnum.type.equals(type) && informationEnum.getValue().equals(value)) {
return informationEnum.key;
}
}
return 0;
}
}
五、调用方法
@ApiOperation("下载模板")
@PostMapping("getExcelTemplate")
public void getExcelTemplate(HttpServletResponse response) {
try {
EasyExcelUtils.webWriteExcelForCommunityPersonnelInformation(response, null, CommunityPersonnelSerumInformationExcelDTO.class, null, "人员血清信息表填写模板");
} catch (IOException e) {
e.printStackTrace();
}
}