公共类
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* POI简历导入工具类
* @author xxx
*/
public class PoiCommon<T> {
private static final Logger logger = LogManager.getLogger();
public PoiCommon() {}
public Row createRow(Sheet sheet, int rowIndex, float rowHeight) {
Row row = sheet.createRow(rowIndex);
row.setHeightInPoints(rowHeight);
return row;
}
/**
* 创建通用Sheet行表头
* @param workbook 工作
* @param sheet sheet
* @param sheetTitleRowIndex 行表头开始位
* @param sheetTitle 头信息
* @param sheetColumnNum 列数量
* @return
*/
public Row createGeneralSheetTitleRow(Workbook workbook, Sheet sheet,
int sheetTitleRowIndex, String sheetTitle, int sheetColumnNum) {
Row sheetTitleRow = createRow(sheet, sheetTitleRowIndex, 35);
CellStyle sheetTitleCellStyle = workbook.createCellStyle();
// 居中
sheetTitleCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// 垂直居中
sheetTitleCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
Font sheetTitleFont = createFont(workbook, (short) 18, Font.BOLDWEIGHT_BOLD, Font.COLOR_NORMAL);
sheetTitleCellStyle.setFont(sheetTitleFont);
createStringCell(sheetTitleRow, 0, sheetTitleCellStyle, sheetTitle);
mergedCell(sheet, sheetTitleRowIndex, 0, sheetTitleRowIndex, sheetColumnNum - 1);
return sheetTitleRow;
}
/**
* 创建通用Sheet表头
* @param workbook
* @param sheet
* @param sheetHeadRowIndex
* @param sheetHead
* @param rowHeight
* @return
*/
public Row createGeneralSheetHeadRow(Workbook workbook, Sheet sheet,
int sheetHeadRowIndex, String[] sheetHead, int rowHeight) {
Row sheetHeadRow = createRow(sheet, sheetHeadRowIndex, rowHeight);
CellStyle sheetHeadCellStyle = workbook.createCellStyle();
// 居中
sheetHeadCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// 垂直居中
sheetHeadCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 下边框
sheetHeadCellStyle.setBorderBottom(CellStyle.BORDER_THICK);
// 左边框
sheetHeadCellStyle.setBorderLeft(CellStyle.BORDER_THICK);
// 上边框
sheetHeadCellStyle.setBorderTop(CellStyle.BORDER_THICK);
// 右边框
sheetHeadCellStyle.setBorderRight(CellStyle.BORDER_THICK);
Font sheetHeadFont = createFont(workbook, (short)12, Font.BOLDWEIGHT_BOLD, Font.COLOR_NORMAL);
sheetHeadCellStyle.setFont(sheetHeadFont);
for (int i = 0; i < sheetHead.length; i++) {
createStringCell(sheetHeadRow, i, sheetHeadCellStyle, sheetHead[i]);
}
return sheetHeadRow;
}
public Row createGeneralCommentRow(Workbook workbook, Sheet sheet, int rowIndex, String commentValue, int sheetColumnNum){
Row commentRow = createRow(sheet, rowIndex, 30);
CellStyle commentCellStyle = workbook.createCellStyle();
commentCellStyle.setAlignment(CellStyle.ALIGN_LEFT);
commentCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
//设置前景色
commentCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//设置填充模式
commentCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
commentCellStyle.setWrapText(true);
Font symbolExplainFont = createFont(workbook, (short)8, Font.BOLDWEIGHT_BOLD, Font.COLOR_NORMAL);
commentCellStyle.setFont(symbolExplainFont);
createStringCell(commentRow, 0, commentCellStyle, commentValue);
mergedCell(sheet, rowIndex, rowIndex, 0, sheetColumnNum - 1);
return commentRow;
}
public CellStyle createGeneralCellStyle(Workbook workbook) {
CellStyle defaultCellStyle = workbook.createCellStyle();
// 居中
defaultCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
// 垂直居中
defaultCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 自动换行
defaultCellStyle.setWrapText(true);
// 下边框
defaultCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
// 左边框
defaultCellStyle.setBorderLeft(CellStyle.BORDER_THIN);
// 上边框
defaultCellStyle.setBorderTop(CellStyle.BORDER_THIN);
// 右边框
defaultCellStyle.setBorderRight(CellStyle.BORDER_THIN);
return defaultCellStyle;
}
public CellStyle createRedFontCellStyle(Workbook workbook) {
CellStyle readFontCellStyle = workbook.createCellStyle();
readFontCellStyle.cloneStyleFrom(createGeneralCellStyle(workbook));
Font readFont = createFont(workbook, (short) 10, Font.BOLDWEIGHT_NORMAL, Font.COLOR_RED);
readFontCellStyle.setFont(readFont);
return readFontCellStyle;
}
public CellStyle createRedFontWithTopBottomBorderCellStyle(Workbook workbook) {
CellStyle readFontCellStyle = workbook.createCellStyle();
readFontCellStyle.cloneStyleFrom(createGeneralCellStyle(workbook));
readFontCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
readFontCellStyle.setBorderTop(CellStyle.BORDER_THIN);
Font readFont = createFont(workbook, (short) 10, Font.BOLDWEIGHT_NORMAL, Font.COLOR_RED);
readFontCellStyle.setFont(readFont);
return readFontCellStyle;
}
public void fixSheetHead(Sheet sheet, int fixRowNum, int fixColNum) {
sheet.createFreezePane(0, fixRowNum, fixColNum, fixRowNum);
}
public Cell createStringCell(Row row, int cellIndex, CellStyle cellStyle, String cellValue) {
Cell cell = row.createCell(cellIndex);
cell.setCellStyle(cellStyle);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
return cell;
}
public Cell createNumericCell(Row row, int cellIndex, CellStyle cellStyle, double cellValue) {
Cell cell = row.createCell(cellIndex);
cell.setCellStyle(cellStyle);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(cellValue);
return cell;
}
public Cell createFormulaCell(Row row, int cellIndex, CellStyle cellStyle, String formula) {
Cell cell = row.createCell(cellIndex);
cell.setCellStyle(cellStyle);
cell.setCellType(Cell.CELL_TYPE_FORMULA);
cell.setCellFormula(formula);
return cell;
}
public Comment createComment(Sheet sheet, String commentValue, String author) {
Drawing patriarch = sheet.createDrawingPatriarch();
Comment comment= patriarch.createCellComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)10,10));
comment.setString(new HSSFRichTextString(commentValue));
comment.setAuthor(author);
return comment;
}
public void mergedCell(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegion(cellRangeAddress);
}
public Font createFont(Workbook workbook, short fontHeight, short boldWeight, short fontColor) {
Font font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints(fontHeight);
// 设置字体加粗
font.setBoldweight(boldWeight);
// 设置字体颜色
font.setColor(fontColor);
return font;
}
public void setColumnWidth(Sheet sheet, int colNum, int width) {
for(int i = 0; i < colNum; i++){
sheet.setColumnWidth(i, width*256);
}
}
public void setColumnWidth(Sheet sheet, int[] columnWidth) {
for (int i = 0; i < columnWidth.length; i++) {
sheet.setColumnWidth(i, columnWidth[i]*256);
}
}
public void setColumnWidthAuto(Sheet sheet, int colNum) {
//设置列的宽度自动调整
for(int i = 0; i < colNum; i++){
sheet.autoSizeColumn(i, true);
}
}
public void writeWorkbookToFile(Workbook workbook, String exportFilePath){
try {
FileOutputStream fos = new FileOutputStream(exportFilePath);
workbook.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
logger.error("Can not found file! Please check the export file path......");
} catch (IOException e) {
logger.error(e);
}
}
public void writeWorkbookToFile(Workbook workbook, OutputStream fos){
try {
workbook.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
logger.error("Can not found file! Please check the export file path......");
} catch (IOException e) {
logger.error(e);
}
}
/*************************************** import Excel file*********************************************/
public Workbook createHSSFWorkBook(InputStream inputStream) {
Workbook workbook = null;
try {
workbook = new HSSFWorkbook(inputStream);
inputStream.close();
} catch (FileNotFoundException e) {
logger.error("Can not found file! Please check the import file path......");
logger.error(e);
} catch (IOException e) {
logger.error("Bring IOExceptoin when new a HSSFWorkbook with good inputStream");
logger.error(e);
}
return workbook;
}
/**
* 返回指定行指定单元格的double类型的值。
* 由于java中用double运算精度会丢失的特性,单元格中值为“10”的值,会解读为两种情况:
* 1. 10.0 (强转为int值为10)
* 2. 9.9999999998 (强转为int值为9)
* @param row
* @param cellIndex
* @return
*/
public Double getRowLocationCellNumericValue(Row row, int cellIndex) {
if(null == row){
return null;
}
Cell cell = row.getCell(cellIndex);
if(null == cell) {
return null;
}
if(Cell.CELL_TYPE_NUMERIC == cell.getCellType()){
return cell.getNumericCellValue();
}
if(Cell.CELL_TYPE_STRING == cell.getCellType() && RegexUtil.isNumeric(cell.getStringCellValue())){
return Double.valueOf(cell.getStringCellValue());
}
if(Cell.CELL_TYPE_FORMULA == cell.getCellType()){
HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook)row.getSheet().getWorkbook());
return formulaEvaluator.evaluate(cell).getNumberValue();
}
return null;
}
public Integer getRowLocationCellIntegerValue(Row row, int cellIndex){
if(null == row){
return null;
}
Cell cell = row.getCell(cellIndex);
if(null == cell) {
return null;
}
if(Cell.CELL_TYPE_NUMERIC == cell.getCellType()){
return (int) Math.round(cell.getNumericCellValue());
}
if(Cell.CELL_TYPE_STRING == cell.getCellType() && RegexUtil.isNumeric(cell.getStringCellValue())){
return (int) Math.round(Double.valueOf(cell.getStringCellValue()));
}
if(Cell.CELL_TYPE_FORMULA == cell.getCellType()){
HSSFFormulaEvaluator formulaEvaluator = new HSSFFormulaEvaluator((HSSFWorkbook)row.getSheet().getWorkbook());
return (int) formulaEvaluator.evaluate(cell).getNumberValue();
}
return null;
}
/**
* 获取String类型的单元格内容(根据行、单元格下标)
* @param row
* @param cellIndex
* @return
*/
public String getRowLocationCellStringValue(Row row, int cellIndex) {
if(null == row){
return null;
}
Cell cell = row.getCell(cellIndex);
if(null == cell) {
return null;
}
if(Cell.CELL_TYPE_STRING != cell.getCellType()){
return null;
}
return cell.getStringCellValue().trim();
}
public String getStringCellValue(Row row, int cellIndex){
if(null == row){
return "";
}
Cell cell = row.getCell(cellIndex);
if(null == cell) {
return "";
}
if(Cell.CELL_TYPE_STRING == cell.getCellType()){
return cell.getStringCellValue().trim();
}
if(Cell.CELL_TYPE_NUMERIC == cell.getCellType()){
// 处理日期格式、时间格式
String result;
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
result = format.format(value);
}
return result;
//return new BigDecimal(cell.getNumericCellValue()).toString();
}
if(Cell.CELL_TYPE_BOOLEAN == cell.getCellType()){
return String.valueOf(cell.getBooleanCellValue());
}
return "";
}
private static boolean checkDate(String str){
String[] dataArr =str.split("-");
try {
if(dataArr.length == 3){
int x = Integer.parseInt(dataArr[0]);
String y = dataArr[1];
int z = Integer.parseInt(dataArr[2]);
if(x>0 && x<32 && z>0 && z< 10000 && y.endsWith("月")){
return true;
}
}
} catch (Exception e) {
return false;
}
return false;
}
public boolean isEmptyRow(Row row) {
int lastCellNum = row.getLastCellNum();
for (int i = 0; i < lastCellNum; i++) {
Cell cell = row.getCell(i);
if(null != cell && !isEmptyCell(cell)){
return false;
}
}
return true;
}
public boolean isEmptyCell(Cell cell) {
if(Cell.CELL_TYPE_BLANK == cell.getCellType()){
return true;
}
if(Cell.CELL_TYPE_STRING == cell.getCellType() && cell.getStringCellValue().isEmpty()){
return true;
}
return false;
}
/**
* based
* @param row
* @return
*/
public int getExcelRowNum(Row row) {
return row.getRowNum() + 1;
}
}
service
import com.pacific.rsp.recruitment.dal.dao.rm.custom.RmResumeMapperCustom;
import com.pacific.rsp.recruitment.model.em.DictionaryEnum;
import com.pacific.rsp.recruitment.model.em.DocumentTypeEnum;
import com.pacific.rsp.recruitment.model.em.ResumeSourceEnum;
import com.pacific.rsp.recruitment.model.po.rm.mbg.RmResume;
import com.pacific.rsp.recruitment.model.po.rm.request.DictionaryParam;
import com.pacific.rsp.recruitment.model.po.rm.request.ResumeBaseInfoParam;
import com.pacific.rsp.recruitment.model.vo.rm.DictionaryView;
import com.pacific.rsp.recruitment.model.vo.rm.ImportResumeView;
import com.pacific.rsp.recruitment.model.vo.rm.SystemRoleBindView;
import com.pacific.rsp.recruitment.util.DateUtil;
import com.pacific.rsp.recruitment.util.PoiCommon;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 导入简历信息
* @author xxx
*/
@Service
public class ImportResumeService {
protected static final Logger logger = LogManager.getLogger();
@Value("${split.resume.path}")
private String splitResumePath;
@Autowired
private DictionaryService dictionaryService;
@Autowired
private ResumeService resumeService;
@Autowired
private BaseService baseService;
@Autowired
private RmResumeMapperCustom resumeMapperCustom;
/**
* 正则表达式
*/
private static final Pattern PATTERN = Pattern.compile("\\s*|\t|\r|\n");
/**
* 手机号码验证
* */
private static final String REGEX_MOBILE = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,0-9])|(18[0,3])|(16[6])|(17[0135678])|(19[89]))\\d{8}$";
/**
* 表头位置
*/
private static final int ROW_HEAD_INDEX = 1;
/**
* 从第几行开始读取
*/
private static final int SHEET_HEADER_ROW_NUM = 2;
/**
* 对象
*/
/**
* 导入简历
* @param inputStream 数据流
* @return
*/
public List<String> importResume(HttpServletRequest request, InputStream inputStream , String userNames) {
PoiCommon poiCommon = new PoiCommon();
List<String> errorMsgList= new ArrayList<>();
List<ImportResumeView> resumeViewList = new ArrayList<>();
int successCount = 0;
int empNoCount = 0;
logger.info("开始读取Excel数据......");
if (inputStream == null){
errorMsgList.add("读取Excel数据流出错,请检查Excel数据流并从新导入...");
errorMsgList.add(String.valueOf(successCount));
return errorMsgList;
}
// 对象初始化
if(poiCommon == null){
poiCommon = new PoiCommon();
}
if (CollectionUtils.isEmpty(errorMsgList)){
errorMsgList = new ArrayList<>();
}else{
errorMsgList.clear();
}
if (CollectionUtils.isEmpty(resumeViewList)){
resumeViewList = new ArrayList<>();
}else{
resumeViewList.clear();
}
// 读取简历信息
Workbook workbook;
List<Sheet> sheetList;
try{
workbook = createHSSFWorkBook(inputStream);
}catch (Exception e){
errorMsgList.add("内部错误,请重新编辑简历模板!");
return errorMsgList;
}
if (null == workbook) {
errorMsgList.add("内部错误,请重新编辑简历模板!");
return errorMsgList;
}
int limitSheetCount = workbook.getNumberOfSheets();
logger.info("sheet count:{}", limitSheetCount);
sheetList = new ArrayList<>();
for (int sheetIndex = 1; sheetIndex < limitSheetCount; sheetIndex++) {
Sheet sheet = workbook.getSheetAt(sheetIndex);
// 获取sheet放到sheetList集合中
if(sheet != null){
sheetList.add(sheet);
}
}
//获取简历数据
resumeViewList = readResumeInfoFromSheet(workbook.getSheetAt(0));
//根据角色code读取招聘专员列表
Set<SystemRoleBindView> recruiterSet = baseService.getRecruiterSet(request);
if(resumeViewList.size() > 200){
errorMsgList.add("最多只能导入200份简历,请重新编辑简历!");
//300标识,返回错误信息(300只是个返回标识)
errorMsgList.add(String.valueOf("300"));
return errorMsgList;
}else if(resumeViewList.size() == 0){
errorMsgList.add("不能导入空简历,请重新编辑导入!");
//000标识,返回错误信息
errorMsgList.add(String.valueOf("000"));
return errorMsgList;
}else{
for (ImportResumeView resumeView : resumeViewList) {
String userName = resumeView.getUserName();
String mobilePhone = resumeView.getMobilePhone();
String recruiterId = resumeView.getRecruiterId();
String recruiter = resumeView.getRecruiter();
String expectedPosition = resumeView.getExpectedPosition();
String inviteDateStr = resumeView.getInviteDate();
Date inviteDate = DateUtil.strToDate(inviteDateStr);
String remark = resumeView.getRemark();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
for (SystemRoleBindView view : recruiterSet) {
if(StringUtils.isNotEmpty(view.getEmpNo()) && recruiterId.equals(view.getEmpNo())){
ResumeBaseInfoParam resumeParam = new ResumeBaseInfoParam();
resumeParam.setResumeName(userName);
resumeParam.setMobilePhone(mobilePhone);
resumeParam.setRecruiterId(recruiterId);
resumeParam.setRecruiter(view.getEmpName());
resumeParam.setExpectedPosition(expectedPosition);//应聘岗位
resumeParam.setStartWorkYear(year);//开始工作年默认设置为当前年
resumeParam.setBirthday(0);//出生年初始设置为当前年
resumeParam.setInviteTime(inviteDate);
resumeParam.setRemark(remark);
resumeParam.setGender((byte)2);//性别初始设置为未知状态
resumeParam.setMarriageStatus((byte)2);//婚姻状态初始设置为保密状态
resumeParam.setJobStatus((byte)3);//设置求职状态为未知
resumeParam.setSource((byte) ResumeSourceEnum.JOB_FAIR.getType());
resumeParam.setSourceWeb(ResumeSourceEnum.JOB_FAIR.getName());
resumeParam.setCreateUser(userNames);
resumeParam.setUpdateUser(userNames);
resumeParam.setUserName(userNames);
//手机号码、招聘专员、应聘岗位和姓名不为空才能导入数据
if((mobilePhone != null && userName != null)
&& (mobilePhone != "" && userName != "")
&& (recruiter != null && recruiter!="")){
//手机号格式验证
Pattern p = Pattern.compile(REGEX_MOBILE);
if(p.matcher(mobilePhone).find()){
Long id = resumeService.addResumeBaseInfo(request , resumeParam);
RmResume resume = resumeMapperCustom.selectByPrimaryKey(id);
if(resume != null){//如果导入成功,成功条数加1
successCount++;
}
}
}
}
}
}
int size = resumeViewList.size()-successCount;
empNoCount = resumeViewList.size()-successCount;
if(CollectionUtils.isEmpty(errorMsgList)){
errorMsgList.add(0, "成功导入" + successCount +"条数据" + ",未成功"+ size +"条数据!");
errorMsgList.add(String.valueOf(successCount));
errorMsgList.add(String.valueOf(empNoCount));
}else {
errorMsgList.add(0, "成功导入" + successCount + "条,"
+ "未成功" + errorMsgList.size() + "条!");
errorMsgList.add(String.valueOf(successCount));
errorMsgList.add(String.valueOf(empNoCount));
}
}
return errorMsgList;
}
/**
* 判定Excel版本
* @param inputStream
* @return
*/
private Workbook createHSSFWorkBook(InputStream inputStream) {
Workbook workbook;
List<String> errorMsgList= new ArrayList<>();
try {
workbook = new XSSFWorkbook(inputStream);
inputStream.close();
} catch (OfficeXmlFileException e) {
errorMsgList.add("表格版本过高,请转为2003版后导入");
return null;
} catch (IOException e) {
errorMsgList.add("内部错误,文件加载失败!");
return null;
}
return workbook;
}
/**
* 读取Excel表中数据并映射成对象
* @param sheet
*/
private List<ImportResumeView> readResumeInfoFromSheet(Sheet sheet){
List<ImportResumeView> resumeViewList = new ArrayList<>();
List<String> errorMsgList= new ArrayList<>();
PoiCommon poiCommon = new PoiCommon();
if (sheet == null){
errorMsgList.add("内部错误,sheet加载失败!");
return null;
}
if (!validateTableHeader(sheet)){
return null;
}
//获取总行数
int lastRowNum = sheet.getLastRowNum();
for (int i = SHEET_HEADER_ROW_NUM; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
String userName = poiCommon.getStringCellValue(row, 0);
String mobilePhone = poiCommon.getStringCellValue(row, 1);
String recruiterId = poiCommon.getStringCellValue(row, 2);
String recruiter = poiCommon.getStringCellValue(row, 3);
String expectedPosition = poiCommon.getStringCellValue(row,4);
String inviteDate = poiCommon.getStringCellValue(row,5);
String remark = poiCommon.getStringCellValue(row,6);
ImportResumeView resumeView = new ImportResumeView();
resumeView.setUserName(userName);
resumeView.setMobilePhone(mobilePhone);
resumeView.setRecruiterId(recruiterId);
resumeView.setRecruiter(recruiter);
resumeView.setExpectedPosition(expectedPosition);
resumeView.setInviteDate(inviteDate);
resumeView.setRemark(remark);
resumeViewList.add(resumeView);
}
return resumeViewList;
}
/**
* 验证表头标题信息
* @param sheet
* @return
*/
private boolean validateTableHeader(Sheet sheet){
// 获取表头
PoiCommon poiCommon = new PoiCommon();
Row row = sheet.getRow(ROW_HEAD_INDEX);
if (null == row) {
return false;
}
String sheetName = sheet.getSheetName();
int rowNum = poiCommon.getExcelRowNum(row);
// 从数据库获取Excel表头信息并进行校验
DictionaryParam dictionaryParam = new DictionaryParam();
dictionaryParam.setDictionaryType(DictionaryEnum.JOB_FAIR_IMPORT.getName());
List<DictionaryView> dictionaryList = dictionaryService.queryDictionaryList(dictionaryParam);
if(CollectionUtils.isNotEmpty(dictionaryList)){
for (DictionaryView view : dictionaryList) {
Byte dictionaryCode = view.getDictionaryCode();
String dictionaryName = view.getDictionaryName();
String userName = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(userName) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String mobilePhone = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(mobilePhone) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String recruiter = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(recruiter) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String recruiterId = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(recruiterId) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String expectedPosition = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(expectedPosition) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String inviteDate = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(inviteDate) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
String remark = poiCommon.getRowLocationCellStringValue(row, dictionaryCode);
if (!dictionaryName.equals(remark) ) {
validateSheetHeader(sheetName, rowNum,dictionaryCode, dictionaryName);
return false;
}
}
}
return true;
}
/**
* 验证Sheet表头标题是否正确
* @param sheetName
* @param rowNum
* @param index
* @param msg
* @return
*/
private String validateSheetHeader(String sheetName, int rowNum, int index, String msg){
List<String> errorMsgList= new ArrayList<>();
StringBuffer buffer = new StringBuffer();
buffer.append("sheet【" + sheetName + "】");
buffer.append("第"+ rowNum +"行");
buffer.append("第"+ (index + 1) +"列的表头格式错误。");
buffer.append("正确格式为:【" + msg + "】");
errorMsgList.add(buffer.toString());
return buffer.toString();
}
/**
* 创建新的Excel
* @param originalSheet 原有sheet文件
* @param newExcelName 新的Excel文件名
*/
public void createNewExcel(Sheet originalSheet,String newExcelName){
HSSFWorkbook newWorkbook = new HSSFWorkbook();
HSSFSheet newSheet = newWorkbook.createSheet(originalSheet.getSheetName());
// 复制源表中的合并单元格
MergerRegion((HSSFSheet) originalSheet, newSheet);
int firstRow = originalSheet.getFirstRowNum();
int lastRow = originalSheet.getLastRowNum();
for (int i = firstRow; i <= lastRow; i++) {
// 创建新建excel Sheet的行
HSSFRow newRow= newSheet.createRow(i);
// 取得原有excel Sheet的行
HSSFRow originalRow = (HSSFRow) originalSheet.getRow(i);
// 单元格式样
int firstCell = originalRow.getFirstCellNum();
int lastCell = originalRow.getLastCellNum();
for (int j = firstCell; j < lastCell; j++) {
newSheet.autoSizeColumn(j);
newRow.createCell(j);
String strVal ="";
if (originalRow.getCell(j) != null) {
strVal = removeInternalBlank(originalRow.getCell(j).getStringCellValue());
}
newRow.getCell(j).setCellValue(strVal);
}
}
try {
FileOutputStream fileOut = new FileOutputStream(
splitResumePath + newExcelName + DocumentTypeEnum.XLS.getName());
newWorkbook.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 复制原有sheet的合并单元格到新创建的sheet
* @param originalSheet 原有的sheet
* @param newSheet 新创建sheet
*/
private static void MergerRegion(HSSFSheet originalSheet, HSSFSheet newSheet) {
int sheetMergerCount = originalSheet.getNumMergedRegions();
for (int i = 0; i < sheetMergerCount; i++) {
newSheet.addMergedRegion(originalSheet.getMergedRegion(i));
}
}
/**
* 去除字符串内部空格
* @param str
* @return
*/
public static String removeInternalBlank(String str) {
Matcher m = PATTERN.matcher(str);
char [] charArray = str.toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == ' ') {
sb.append(' ');
}else{
break;
}
}
String after = m.replaceAll("");
return sb.toString() + after;
}
}
controller
import com.pacific.rsp.recruitment.model.em.ErrorCodeEnum;
import com.pacific.rsp.recruitment.service.ImportResumeService;
import com.pacific.rsp.recruitment.util.JsonResult;
import com.pacific.rsp.recruitment.web.controller.BaseController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
/**
* 导入控制器
* @author xxx
*/
@RestController
@RequestMapping("api/rm/import")
public class ImportResumeController extends BaseController{
@Autowired
private ImportResumeService importResumeService;
@ApiOperation(value = "导入简历",notes = "导入简历")
@RequestMapping(value = "/importResume",method = RequestMethod.POST)
public JsonResult importResume(HttpServletRequest request,
@RequestParam(value = "file",required = false) MultipartFile multipartFile , @RequestParam(value="userName") String userNames) {
List<String> list;
String filename = multipartFile.getOriginalFilename();
JsonResult jsonResult = new JsonResult();
boolean isExce = filename.toLowerCase().endsWith("xls") || filename.toLowerCase().endsWith("xlsx")?true:false;
try {
if(isExce){
list = importResumeService.importResume(request, multipartFile.getInputStream() , userNames);
}else{
jsonResult.setSuccess(false);
jsonResult.setMsg("导入文件格式错误");
return jsonResult;
}
}catch (IOException e) {
return JsonResult.error(ErrorCodeEnum.FAILURE.getCode(),ErrorCodeEnum.FAILURE.getMsg());
}
if(list != null && list.size() == 1){
jsonResult.setSuccess(false);
jsonResult.setMsg(list.get(0));
return jsonResult;
}
if(list.get(1).equals("300")){
jsonResult.setSuccess(false);
jsonResult.setMsg(list.get(0));
return jsonResult;
}
if(list.get(1).equals("000")){
jsonResult.setSuccess(false);
jsonResult.setMsg(list.get(0));
return jsonResult;
}
if(list.get(1).equals("0")){
jsonResult.setSuccess(false);
jsonResult.setMsg("导入失败,其中有"+list.get(2)+"条因招聘专员不匹配、姓名或手机号未通过验证未导入!");
}else if(!"0".equals(list.get(2)) && !list.get(1).equals("0")){
jsonResult.setSuccess(false);
jsonResult.setMsg("成功导入"+list.get(1)+"条,其中有"+list.get(2)+"条因招聘专员不匹配、姓名或手机号未通过验证未导入!");
}else if(list.get(2).equals("0") && list.size() > 3 && list.get(3).equals("0")){
jsonResult.setSuccess(false);
jsonResult.setMsg(list.get(1));
}else{
jsonResult.setSuccess(true);
jsonResult.setMsg("全部导入成功!");
}
return jsonResult;
}
}