导入导出

This commit is contained in:
mash 2023-02-14 15:36:30 +08:00
parent b1a25a0d9f
commit 4f0b6463d5
15 changed files with 1031 additions and 15 deletions

View File

@ -0,0 +1,48 @@
package com.ydool.common.converter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
* @author msh
* @version 1.0
* @date 2023/2/13 17:19
*/
public class EasyExcelLocalDateConverter implements Converter<LocalDate> {
@Override
public Class<LocalDate> supportJavaTypeKey() {
return LocalDate.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
if (cellData.getType().equals(CellDataTypeEnum.NUMBER)){
LocalDate localDate = LocalDate.of(1900, 1, 1);
localDate = localDate.plusDays(cellData.getNumberValue().longValue() - 2);
return localDate;
}else if (cellData.getType().equals(CellDataTypeEnum.STRING)){
return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}else {
return null;
}
}
@Override
public CellData<LocalDate> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
}

View File

@ -0,0 +1,67 @@
package com.ydool.common.handler;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import java.util.List;
import java.util.Map;
/**
* @author liuhaoze
* @date 2021/12/17 10:13
*/
public class ExcelDataValidationHandler implements CellWriteHandler {
private Map<Integer, String[]> dataValidation;
public ExcelDataValidationHandler(Map<Integer, String[]> dataValidation){
this.dataValidation = dataValidation;
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if(isHead){
Sheet sheet = writeSheetHolder.getSheet();
DataValidationHelper helper = sheet.getDataValidationHelper();
dataValidation.forEach((k, v) -> {
// 设置下拉单元格的首行 末行 首列 末列
CellRangeAddressList rangeList = new CellRangeAddressList(1, 100000, k, k);
// 下拉列表约束数据
DataValidationConstraint constraint = helper.createExplicitListConstraint(v);
// 设置约束
DataValidation validation = helper.createValidation(constraint, rangeList);
// 阻止输入非下拉选项的值
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
validation.setShowErrorBox(true);
validation.setSuppressDropDownArrow(true);
validation.createErrorBox("提示", "此值与单元格定义格式不一致");
sheet.addValidationData(validation);
});
}
}
}

View File

@ -0,0 +1,164 @@
package com.ydool.common.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
/**
* 基于EasyExcel的导入导出工具类 在使用时需要先将excel实体类中的字段使用@ExcelProperty来指定表头
* {@link com.alibaba.excel.annotation.ExcelProperty}
* {@link com.alibaba.excel.annotation.write.style.ColumnWidth}
* {@link com.alibaba.excel.annotation.format.DateTimeFormat}
*/
public class EasyExcelAlibabaUtil {
private static Log logger = LogFactory.getLog("EasyExcelAlibabaUtil");
/**
* 将excel文件转化成javaList集合
* 需要在传入的class的字段中加入EasyExcel的专用注解来指定表名
*
* @param excelFile 前端传入的文件
* @param clazz 一个Class对象
* @param <T>
* @return 可以直接转成传入的Class的List集合
*/
public static <T> List<T> excelToList(MultipartFile excelFile, Class<T> clazz) {
List<T> objects = null;
try {
InputStream inputStream = excelFile.getInputStream();
objects = EasyExcel.read(inputStream).head(clazz).sheet().doReadSync();
} catch (Exception e) {
logger.error("excelToList-exception", e);
} finally {
return objects;
}
}
/**
* 读取excel这个相当于一个高性能模式
* 比上面的方法多了一个readListener接口 需要传一个实现这个接口的实现类
* 其中invoke方法是每读取一行都会调用 所以可以读取一行处理一行 性能比较高
*
* @param excelFile
* @param clazz
* @param readListener
*/
public static void readExcelHighPerformance(MultipartFile excelFile, Class<T> clazz, ReadListener readListener) {
try {
InputStream inputStream = excelFile.getInputStream();
EasyExcel.read(inputStream, clazz, readListener).sheet().doRead();
} catch (Exception e) {
logger.error("excelToList-readExcelHighPerformance", e);
}
}
/**
* 下载excel
*
* @param response web项目中response对象
* @param clazz Class对象 需要读取这个Class中的字段注解的名称 用于生成表头
* @param list java的List集合需要与传入的Class匹配
* @param excelName 需要生成的excel名称
*/
public static void download(HttpServletResponse response, Class<?> clazz, List<?> list, String excelName) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(excelName, "UTF-8"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
EasyExcel.write(baos, clazz).sheet("sheet1").doWrite(list);
response.setHeader("Content-Length", String.valueOf(baos.size()));
outputStream.write(baos.toByteArray());
response.flushBuffer();
} catch (Exception e) {
logger.error("excelToList-download", e);
}
}
/**
* 下载excel
*
* @param clazz Class对象 需要读取这个Class中的字段注解的名称 用于生成表头
* @param list java的List集合需要与传入的Class匹配
* @param excelName 需要生成的excel名称
*/
public static String download(Class<?> clazz, List<?> list, String excelName) {
//文件名称
String fileName = excelName + IdUtil.randomUUID() + ".xlsx";
//文件存放目录
String urlPath = getWebRoot() + getFileUploadPath();
//文件路径
String fileNamePath = urlPath + File.separator + fileName;
//文件存放目录不存在则新建
File pathFile = new File(urlPath);
if (!pathFile.exists()) pathFile.mkdirs();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
EasyExcel.write(baos, clazz).sheet("sheet1").doWrite(list);
//生成excel文件
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fileNamePath);
fileOutputStream.write(baos.toByteArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
logger.error("excelToList-download", e);
}
return getFileUploadPath() + File.separator + fileName;
}
/**
* 文件名
*
* @param excelName
* @return
*/
public static String getFileNamePath(String excelName) {
String fileName = excelName + IdUtil.randomUUID() + ".xlsx";//文件名称
String folder = DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd");//当天文件夹名称
String urlPath = System.getProperty("user.dir") + File.separator + "upload" + File.separator + folder; //文件存放路径
String fileNamePath = urlPath + File.separator + fileName;
return fileNamePath;
}
public static String getFileUploadPath() {
String folder = DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd");
return File.separator + "upload" + File.separator + "excel" + File.separator + folder;
}
public static String getRtspUploadPath() {
String folder = "rtsp";
return File.separator + "upload" + File.separator + folder;
}
public static String getWebRoot() {
return System.getProperty("user.dir");
}
}

View File

@ -0,0 +1,108 @@
package com.ydool.common.utils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* @author liuhaoze
* @date 2022/5/27 14:45
*/
public class ExcelMergeRowByRowUtil implements RowWriteHandler {
private int mergeRowIndex;//从哪一行开始合并
private int[] mergeColumnIndex;//excel合并的列
private int signNum;//合并的唯一标识
private int total;//总行数
private int lastRow;
private int firstCol;
private int lastCol;
private int firstRow;
private int mergeCount =1;
public ExcelMergeRowByRowUtil(int mergeRowIndex, int[] mergeColumnIndex, int signNum, int total) {
this.mergeRowIndex = mergeRowIndex;
this.mergeColumnIndex = mergeColumnIndex;
this.signNum = signNum;
this.total = total;
}
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
//当前行
int curRowIndex = row.getRowNum();
//每一行的最大列数
short lastCellNum = row.getLastCellNum();
if(curRowIndex == 1){
//赋初值 第一行
firstRow = curRowIndex;
}
//开始合并位置
if(curRowIndex > mergeRowIndex && !row.getCell(0).getStringCellValue().equals("")){
for (int i = 0; i < lastCellNum; i++) {
if(i == mergeColumnIndex[i]){
//当前行号 当前行对象 合并的标识位
mergeWithPrevAnyRow(writeSheetHolder.getSheet(),curRowIndex,row,signNum);
break;//已经进入到合并单元格操作里面了执行一次就行
}
}
}
}
public void mergeWithPrevAnyRow(Sheet sheet,int curRowIndex,Row row,int signNum){
Object currentData = row.getCell(signNum).getCellTypeEnum() == CellType.STRING ? row.getCell(signNum).getStringCellValue() : row.getCell(signNum).getNumericCellValue();
Row preRow = row.getSheet().getRow(curRowIndex - 1);
Object preData = preRow.getCell(signNum).getCellTypeEnum() == CellType.STRING ? preRow.getCell(signNum).getStringCellValue() : preRow.getCell(signNum).getNumericCellValue();
//判断是否合并单元格
boolean curEqualsPre = currentData.equals(preData);
//判断前一个和后一个相同 并且 标识位相同
if (curEqualsPre){
lastRow = curRowIndex;
mergeCount++;
}
//excel过程中合并
if(!curEqualsPre && mergeCount>1){
mergeSheet(firstRow,lastRow,mergeColumnIndex,sheet);
mergeCount = 1;
}
//excel结尾处合并
if (mergeCount>1 && total==curRowIndex){
mergeSheet(firstRow,lastRow,mergeColumnIndex,sheet);
mergeCount = 1;
}
if (!curEqualsPre){
firstRow = curRowIndex;
}
}
private void mergeSheet(int firstRow, int lastRow, int[] mergeColumnIndex, Sheet sheet){
for (int colNum : mergeColumnIndex){
firstCol = colNum;
lastCol = colNum;
CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow,lastRow,firstCol,lastCol);
sheet.addMergedRegion(cellRangeAddress);
}
}
}

View File

@ -0,0 +1,107 @@
package com.ydool.common.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.ydool.common.exception.ResultException;
import com.ydool.common.handler.ExcelDataValidationHandler;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
public static void export(String fileName, List<List<String>> head, String sheetName, List data) {
try {
HttpServletResponse response = HttpServletUtil.getResponse();
response.reset();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(head).registerWriteHandler(getHorizontalCellStyleStrategy()).sheet(sheetName).doWrite(data);
}catch (Exception e) {
e.printStackTrace();
throw new ResultException("下载模板文件失败");
}
}
public static void export(String fileName, List<List<String>> head, Map<Integer, String[]> dataValidation, String sheetName, List data) {
try {
HttpServletResponse response = HttpServletUtil.getResponse();
response.reset();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(head).registerWriteHandler(getHorizontalCellStyleStrategy()).registerWriteHandler(new ExcelDataValidationHandler(dataValidation)).sheet(sheetName).doWrite(data);
}catch (Exception e) {
e.printStackTrace();
throw new ResultException("下载模板文件失败");
}
}
public static void export(String fileName, Class head, String sheetName, List data) {
try {
HttpServletResponse response = HttpServletUtil.getResponse();
response.reset();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(head).autoTrim(false).registerWriteHandler(getHorizontalCellStyleStrategy()).sheet(sheetName).doWrite(data);
}catch (Exception e) {
e.printStackTrace();
throw new ResultException("下载失败");
}
}
public static void export(String fileName, Class head,ExcelMergeRowByRowUtil excelMergeRowByRowStrategy, String sheetName, List data) {
try {
HttpServletResponse response = HttpServletUtil.getResponse();
response.reset();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream()).head(head).autoTrim(false).registerWriteHandler(getHorizontalCellStyleStrategy()).registerWriteHandler(excelMergeRowByRowStrategy).sheet(sheetName).doWrite(data);
}catch (Exception e) {
e.printStackTrace();
throw new ResultException("下载失败");
}
}
public static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy() {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)9);
headWriteFont.setFontName("宋体");
headWriteFont.setBold(false);//设置字体不加粗
headWriteCellStyle.setWriteFont(headWriteFont);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景白色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
// 字体
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short)9);
contentWriteFont.setFontName("宋体");
contentWriteFont.setBold(false); //设置字体不加粗
contentWriteCellStyle.setWriteFont(contentWriteFont);
//边框
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
HorizontalCellStyleStrategy horizontalCellStyleStrategy =
new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
return horizontalCellStyleStrategy;
}
}

View File

@ -9,6 +9,7 @@ import com.ydool.common.utils.UploadUtils;
import com.ydool.staff.dto.PersonnelDto;
import com.ydool.staff.dto.PersonnelUpdateDto;
import com.ydool.staff.entity.Attachment;
import com.ydool.staff.entity.Personnel;
import com.ydool.staff.entity.SelectRequest;
import com.ydool.staff.request.ChangeRequest;
import com.ydool.staff.request.PersonnelDeleteRequest;
@ -24,8 +25,11 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
@ -83,7 +87,24 @@ public class PersonnelController extends BaseController {
return personnelService.updateChange(request);
}
@GetMapping("export")
@ApiOperation(value = "导出接口")
public void export(){
personnelService.export();
}
/**
* 导入员工
*
* @param excl
* @throws Exception
*/
@ApiOperation("导入员工")
@PostMapping(value = "importPersonnel")
public void importEmployees(@RequestParam("file") @NotNull(message = "file is null") MultipartFile excl) throws Exception {
AjaxResult ajaxResult = personnelService.importPersonnel(excl);
renderJson(ajaxResult);
}
}

View File

@ -29,7 +29,7 @@ public class PersonnelUpdateDto {
private String companyName;
@ApiModelProperty(value = "性别")
private Integer gender;
private String gender;
@ApiModelProperty(value = "出生日期")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ -48,7 +48,7 @@ public class PersonnelUpdateDto {
private String education;
@ApiModelProperty(value = "是否应届毕业生")
private Integer freshGraduate;
private String freshGraduate;
@ApiModelProperty(value = "毕业院校")
private String academy;

View File

@ -42,7 +42,7 @@ public class Personnel extends BaseEntity {
private String companyName;
@ApiModelProperty(value = "性别")
private Integer gender;
private String gender;
@ApiModelProperty(value = "出生日期")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ -61,7 +61,7 @@ public class Personnel extends BaseEntity {
private String education;
@ApiModelProperty(value = "是否应届毕业生")
private Integer freshGraduate;
private String freshGraduate;
@ApiModelProperty(value = "毕业院校")
private String academy;

View File

@ -0,0 +1,51 @@
package com.ydool.staff.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.ydool.common.converter.EasyExcelLocalDateConverter;
import lombok.Data;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.time.LocalDate;
/**
* @author msh
* @version 1.0
* @date 2023/2/13 17:05
*/
@Data
@HeadRowHeight(20)
@ColumnWidth(20)
@HeadStyle(horizontalAlignment = HorizontalAlignment.CENTER)
@ContentStyle(verticalAlignment = VerticalAlignment.CENTER)
public class ExcelPersonnel {
@ExcelProperty("姓名")
private String userName;
@ColumnWidth(40)
@ExcelProperty("身份证号")
private String numberId;
@ExcelProperty("企业名称")
private String companyName;
@ExcelProperty("所在部门")
private String presentDept;
@ExcelProperty("人员类型")
private String personnelType;
@ExcelProperty(value = "创建时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate createdAt;
@ExcelProperty("变更标志")
private String alterationSign;
}

View File

@ -0,0 +1,150 @@
package com.ydool.staff.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.ydool.common.converter.EasyExcelLocalDateConverter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PersonnelExportVO {
@ExcelProperty("统一社会信用代码")
private String socialCreditCode;
@ExcelProperty("姓名")
private String userName;
@ExcelProperty("企业名称")
private String companyName;
@ExcelProperty("性别")
private String gender;
@ExcelProperty(value = "出生日期" , converter = EasyExcelLocalDateConverter.class)
private LocalDate birthday;
@ExcelProperty("身份证号")
private String numberId;
@ExcelProperty("民族")
private String nation;
@ExcelProperty("政治面貌")
private String politicsStatus;
@ExcelProperty("学历")
private String education;
@ExcelProperty("是否应届毕业生")
private String freshGraduate;
@ExcelProperty("毕业院校")
private String academy;
@ExcelProperty("专业")
private String specialty;
@ExcelProperty("录用方式")
private String hireType;
@ExcelProperty("执业资格证书")
private String qualification;
@ExcelProperty("专业技术职称")
private String jobTitle;
@ExcelProperty("所在部门")
private String presentDept;
@ExcelProperty("岗位职务")
private String position;
@ExcelProperty("合同形式")
private String contractModality;
@ExcelProperty("人员类型")
private String personnelType;
@ExcelProperty("工作状态")
private String workState;
@ExcelProperty("人员性质")
private String personnelCharacter;
@ExcelProperty("年薪")
private Integer annualSalary;
@ExcelProperty(value = "入职时间" , converter = EasyExcelLocalDateConverter.class)
private LocalDate hireDate;
@ExcelProperty(value = "退休时间", converter = EasyExcelLocalDateConverter.class)
private LocalDate retirementTime;
@ExcelProperty(value ="离职时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate resignationTime;
@ExcelProperty(value = "退休返聘开始时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate txfpStartTime;
@ExcelProperty(value = "退休返聘结束时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate txfpEndTime;
@ExcelProperty("人员招聘单号")
private String recruitNumber;
@ExcelProperty("备注")
private String remark;
@ExcelProperty("初审意见")
private String firstTrialRemark;
@ExcelProperty("终审意见")
private String finalTrialRemark;
@ExcelProperty("变更标志")
private String alterationSign;
@ExcelProperty("单据状态")
private String receipts;
}

View File

@ -0,0 +1,154 @@
package com.ydool.staff.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.ydool.common.converter.EasyExcelLocalDateConverter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
/**
* @author msh
* @version 1.0
* @date 2023/2/14 11:55
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PersonnelFailMsgVO {
@ExcelProperty("统一社会信用代码")
private String socialCreditCode;
@ExcelProperty("姓名")
private String userName;
@ExcelProperty("企业名称")
private String companyName;
@ExcelProperty("性别")
private String gender;
@ExcelProperty(value = "出生日期" , converter = EasyExcelLocalDateConverter.class)
private LocalDate birthday;
@ExcelProperty("身份证号")
private String numberId;
@ExcelProperty("民族")
private String nation;
@ExcelProperty("政治面貌")
private String politicsStatus;
@ExcelProperty("学历")
private String education;
@ExcelProperty("是否应届毕业生")
private String freshGraduate;
@ExcelProperty("毕业院校")
private String academy;
@ExcelProperty("专业")
private String specialty;
@ExcelProperty("录用方式")
private String hireType;
@ExcelProperty("执业资格证书")
private String qualification;
@ExcelProperty("专业技术职称")
private String jobTitle;
@ExcelProperty("所在部门")
private String presentDept;
@ExcelProperty("岗位职务")
private String position;
@ExcelProperty("合同形式")
private String contractModality;
@ExcelProperty("人员类型")
private String personnelType;
@ExcelProperty("工作状态")
private String workState;
@ExcelProperty("人员性质")
private String personnelCharacter;
@ExcelProperty("年薪")
private Integer annualSalary;
@ExcelProperty(value = "入职时间" , converter = EasyExcelLocalDateConverter.class)
private LocalDate hireDate;
@ExcelProperty(value = "退休时间", converter = EasyExcelLocalDateConverter.class)
private LocalDate retirementTime;
@ExcelProperty(value ="离职时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate resignationTime;
@ExcelProperty(value = "退休返聘开始时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate txfpStartTime;
@ExcelProperty(value = "退休返聘结束时间",converter = EasyExcelLocalDateConverter.class)
private LocalDate txfpEndTime;
@ExcelProperty("人员招聘单号")
private String recruitNumber;
@ExcelProperty("备注")
private String remark;
@ExcelProperty("初审意见")
private String firstTrialRemark;
@ExcelProperty("终审意见")
private String finalTrialRemark;
@ExcelProperty("变更标志")
private String alterationSign;
@ExcelProperty("单据状态")
private String receipts;
@ExcelProperty(value = "结果")
private String failMsg;
}

View File

@ -32,7 +32,7 @@ public class PersonnelRequest {
@ApiModelProperty(value = "性别")
@NotNull(message = "性别不能为空")
private Integer gender;
private String gender;
@ApiModelProperty(value = "出生日期")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@ -56,7 +56,7 @@ public class PersonnelRequest {
@ApiModelProperty(value = "是否应届毕业生")
@NotNull(message = "是否应届毕业生不能为空")
private Boolean freshGraduate;
private String freshGraduate;
@ApiModelProperty(value = "毕业院校")
@NotBlank(message = "毕业院校不能为空")

View File

@ -35,7 +35,7 @@ public class PersonnelUpdateRequest {
@ApiModelProperty(value = "是否应届毕业生")
@NotBlank(message = "是否应届毕业生不能为空")
private Integer freshGraduate;
private String freshGraduate;
@ApiModelProperty(value = "毕业院校")
@NotBlank(message = "毕业院校不能为空")

View File

@ -2,12 +2,15 @@ package com.ydool.staff.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ydool.common.data.dto.AjaxResult;
import com.ydool.staff.entity.Personnel;
import com.ydool.staff.entity.SelectRequest;
import com.ydool.staff.request.ChangeRequest;
import com.ydool.staff.request.PersonnelDeleteRequest;
import com.ydool.staff.request.PersonnelRequest;
import com.ydool.staff.request.PersonnelUpdateRequest;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
@ -56,5 +59,9 @@ public interface IPersonnelService {
* @return
*/
AjaxResult updateChange(ChangeRequest request);
void export();
AjaxResult importPersonnel(MultipartFile excl);
}

View File

@ -1,10 +1,15 @@
package com.ydool.staff.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@ -12,6 +17,9 @@ import com.ydool.common.base.BaseService;
import com.ydool.common.constant.ArgsConst;
import com.ydool.common.data.dto.AjaxResult;
import com.ydool.common.utils.ColumnUtil;
import com.ydool.common.utils.EasyExcelAlibabaUtil;
import com.ydool.common.utils.ExcelMergeRowByRowUtil;
import com.ydool.common.utils.ExcelUtil;
import com.ydool.staff.dto.AttachmentDto;
import com.ydool.staff.dto.PersonnelByExchangeDto;
import com.ydool.staff.dto.PersonnelDto;
@ -19,12 +27,13 @@ import com.ydool.staff.dto.PersonnelUpdateDto;
import com.ydool.staff.entity.Alteration;
import com.ydool.staff.entity.Attachment;
import com.ydool.staff.entity.CompanyName;
import com.ydool.staff.entity.Organization;
import com.ydool.staff.entity.Personnel;
import com.ydool.staff.entity.SelectRequest;
import com.ydool.staff.excel.ExcelPersonnel;
import com.ydool.staff.excel.PersonnelExportVO;
import com.ydool.staff.excel.PersonnelFailMsgVO;
import com.ydool.staff.mapper.AlterationMapper;
import com.ydool.staff.mapper.CompanyNameMapper;
import com.ydool.staff.mapper.OrganizationMapper;
import com.ydool.staff.mapper.PersonnelMapper;
import com.ydool.staff.request.AttachmentRequest;
import com.ydool.staff.request.ChangeRequest;
@ -37,15 +46,15 @@ import com.ydool.system.entity.Dept;
import com.ydool.system.mapper.DeptMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;
import javax.annotation.Resource;
import javax.validation.constraints.Null;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@ -84,8 +93,12 @@ public class PersonnelServiceImpl extends BaseService<PersonnelMapper, Personnel
PersonnelDto dto = BeanUtil.copyProperties(e, PersonnelDto.class);
CompanyName companyName = companyNameMapper.selectById(e.getCompanyName());
Dept dept = deptMapper.selectById(e.getPresentDept());
dto.setPresentDept(dept.getName());
if (ObjectUtil.isNotNull(companyName)){
dto.setCompanyName(companyName.getCompanyName());
}
if (ObjectUtil.isNotNull(dept)) {
dto.setPresentDept(dept.getName());
}
dto.setCreatedAt(e.getCreatedAt());
return dto;
}).collect(Collectors.toList()));
@ -122,6 +135,10 @@ public class PersonnelServiceImpl extends BaseService<PersonnelMapper, Personnel
@Override
@Transactional(rollbackFor = Exception.class)
public AjaxResult savePersonnel(PersonnelRequest personnelRequest) {
if (!IdcardUtil.isValidCard(personnelRequest.getNumberId())){
return AjaxResult.fail().msg("身份证号格式不正确!");
}
Personnel personnel = BeanUtil.copyProperties(personnelRequest, Personnel.class);
personnel.setCardFile(StringUtils.join(saveFilePath(personnelRequest.getCardFile(), ArgsConst.CARD_FILE, ArgsConst.SAVE, ""), ','));
personnel.setEngageFile(StringUtils.join(saveFilePath(personnelRequest.getEngageFile(), ArgsConst.ENGAGE_FILE, ArgsConst.SAVE, ""), ','));
@ -343,5 +360,127 @@ public class PersonnelServiceImpl extends BaseService<PersonnelMapper, Personnel
}
return wrapper;
}
public void export() {
List<Personnel> list = list();
List<ExcelPersonnel> personnelList = BeanUtil.copyToList(list, ExcelPersonnel.class);
for (ExcelPersonnel excelPersonnel : personnelList) {
CompanyName companyName = companyNameMapper.selectById(excelPersonnel.getCompanyName());
Dept dept = deptMapper.selectById(excelPersonnel.getPresentDept());
if (ObjectUtil.isNotEmpty(companyName)){
excelPersonnel.setCompanyName(companyName.getCompanyName());
}
if (ObjectUtil.isNotEmpty(dept)){
excelPersonnel.setPresentDept(dept.getName());
}
}
int[] mergeColumeIndex = {0};//需要合并的列
int mergeRowIndex = 100;// 从那一行开始合并
ExcelMergeRowByRowUtil excelMergeRowByRowStrategy = new ExcelMergeRowByRowUtil(mergeRowIndex,mergeColumeIndex,mergeColumeIndex[0],personnelList.size());
ExcelUtil.export(URLUtil.encode(DateUtil.format(new Date(),"yyyyMMdd")+"人员表"), ExcelPersonnel.class,excelMergeRowByRowStrategy,"sheet1",personnelList);
}
@Override
public AjaxResult importPersonnel(MultipartFile excl) {
//判断文件类型
String reg = ".+(.xlsx)$";
String suffix = FileUtil.getSuffix(excl.getOriginalFilename());
if (!Pattern.matches(reg, excl.getOriginalFilename()))
return AjaxResult.fail("必须上传后缀为" + suffix + "的文件");
System.out.println("准备导入通讯录" + excl);
if (!"企业人员申报模板.xlsx".equals(excl.getOriginalFilename()))
return AjaxResult.fail("必须上传 企业人员申报模板.xlsx 文件");
//导出数据
List<PersonnelFailMsgVO> failList = new ArrayList<>();
//保存数据
// List<Employees> employeesList = new ArrayList<Employees>();
if (!excl.isEmpty()) {
List<PersonnelExportVO> personnelExportVOS = EasyExcelAlibabaUtil.excelToList(excl,
PersonnelExportVO.class);
JSON json = JSONUtil.parseObj(personnelExportVOS);
System.out.println("导入人员信息:" + json + personnelExportVOS);
System.out.println("导入企业人员申报表:" + personnelExportVOS.size() + "");
if (CollectionUtil.isEmpty(personnelExportVOS)){
return AjaxResult.fail("模板必须要有数据");
}
for (PersonnelExportVO personnelExportVO : personnelExportVOS) {
System.out.println("通讯录信息" + personnelExportVO);
//校验通讯录信息
PersonnelFailMsgVO failMsgVO = checkPersonnelExportVO(personnelExportVO);
//错误数据 不保存
if (StrUtil.isNotBlank(failMsgVO.getFailMsg())) {
System.out.println("2222222222222 = ");
failList.add(failMsgVO);
} else {
System.out.println(" 111111111 ");
//转义
Personnel personnel = interpretPersonnelExportVO(personnelExportVO);
System.out.println("personnel = " + personnel);
//保存
failMsgVO.setFailMsg(failMsgVO.getFailMsg() + (save(personnel) ? "导入成功" : "导入失败"));
failList.add(failMsgVO);
}
}
//保存
// if (CollectionUtil.isNotEmpty(employeesList)) {
// saveBatch(employeesList);
// }
}
// String fileName="通讯录导入结果.xlsx";//文件名称
// String urlPath = System.getProperty("user.dir") + File.separator + "upload"; //文件存放路径
// String FileNamePath = urlPath + File.separator + fileName;
// FileOutputStream fis=new FileOutputStream(FileNamePath);
// OutputStreamWriter out = new OutputStreamWriter(fis,"UTF-8");
//导出导入结果
String download = EasyExcelAlibabaUtil.download(PersonnelFailMsgVO.class, failList, "通讯录导入结果");
return AjaxResult.ok().data(download).msg("导入完成");
}
public PersonnelFailMsgVO checkPersonnelExportVO(PersonnelExportVO personnelExportVO) {
PersonnelFailMsgVO failMsgVO = BeanUtil.copyProperties(personnelExportVO, PersonnelFailMsgVO.class);
failMsgVO.setFailMsg("");
//联系人姓名不能为空
if (StrUtil.isBlank(personnelExportVO.getUserName())) {
failMsgVO.setFailMsg(failMsgVO.getFailMsg() + " 姓名不能为空 ");
}
//校验性别
if (!"".equals(personnelExportVO.getGender()) && !"".equals(personnelExportVO.getGender())) {
failMsgVO.setFailMsg(failMsgVO.getFailMsg() + " 请输入正确性别,男或女 ");
}
//校验性别
if (!"".equals(personnelExportVO.getFreshGraduate()) && !"".equals(personnelExportVO.getGender())) {
failMsgVO.setFailMsg(failMsgVO.getFailMsg() + " 请输入正确选项,是或否 ");
}
/* //加密
String phone = employeesExportVO.getPhone();*/
/*int count = count(new LambdaQueryWrapper<Personnel>()
.eq(Personnel::getNumberId, personnelExportVO.getNumberId()));
if (count > 0) {
failMsgVO.setFailMsg(failMsgVO.getFailMsg() + " 身份证已存在 ");
}*/
return failMsgVO;
}
public Personnel interpretPersonnelExportVO(PersonnelExportVO personnelExportVO) {
Personnel personnel = BeanUtil.copyProperties(personnelExportVO, Personnel.class);
/*//手机号码加密
employees.setPhone(CodecUtils.encrypt(employees.getPhone()));*/
//组织编码转组织Id
/* GrapeDept dept = deptService.getOne(new LambdaQueryWrapper<GrapeDept>().eq(GrapeDept::getCode,
employeesExportVO.getDeptCode()));*/
//性别转换
//personnel.setGender("".equals(personnelExportVO.getGender()) ? 1 : 0);
personnel.setFreshGraduate("".equals(personnelExportVO.getFreshGraduate()) ? "1" : "0");
return personnel;
}
}