32.員工資料匯出(Excel匯出)
阿新 • • 發佈:2020-08-10
匯出
EmployeeController
@GetMapping("/export")
public ResponseEntity<byte[]> exportData(){
List<Employee> list =
(List<Employee>)employeeService.getEmployeeByPage(null,null,null).getData();
return POIUtils.employee2Excel(list);
}
POIUtils
//匯出 public static ResponseEntity<byte[]> employee2Excel(List<Employee> list) { //1. 建立一個 Excel 文件 HSSFWorkbook workbook = new HSSFWorkbook(); //2. 建立文件摘要 workbook.createInformationProperties(); //3. 獲取並配置文件資訊 DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation(); //文件類別 docInfo.setCategory("員工資訊"); //文件管理員 docInfo.setManager("javaboy"); //設定公司資訊 docInfo.setCompany("www.javaboy.org"); //4. 獲取文件摘要資訊 SummaryInformation summInfo = workbook.getSummaryInformation(); //文件標題 summInfo.setTitle("員工資訊表"); //文件作者 summInfo.setAuthor("javaboy"); // 文件備註 summInfo.setComments("本文件由 javaboy 提供"); //5. 建立樣式 //建立標題行的樣式 HSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); HSSFCellStyle dateCellStyle = workbook.createCellStyle(); dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); HSSFSheet sheet = workbook.createSheet("員工資訊表"); //設定列的寬度 sheet.setColumnWidth(0, 5 * 256); sheet.setColumnWidth(1, 12 * 256); sheet.setColumnWidth(2, 10 * 256); sheet.setColumnWidth(3, 5 * 256); sheet.setColumnWidth(4, 12 * 256); sheet.setColumnWidth(5, 20 * 256); sheet.setColumnWidth(6, 10 * 256); sheet.setColumnWidth(7, 10 * 256); sheet.setColumnWidth(8, 16 * 256); sheet.setColumnWidth(9, 12 * 256); sheet.setColumnWidth(10, 15 * 256); sheet.setColumnWidth(11, 20 * 256); sheet.setColumnWidth(12, 16 * 256); sheet.setColumnWidth(13, 14 * 256); sheet.setColumnWidth(14, 14 * 256); sheet.setColumnWidth(15, 12 * 256); sheet.setColumnWidth(16, 8 * 256); sheet.setColumnWidth(17, 20 * 256); sheet.setColumnWidth(18, 20 * 256); sheet.setColumnWidth(19, 15 * 256); sheet.setColumnWidth(20, 8 * 256); sheet.setColumnWidth(21, 25 * 256); sheet.setColumnWidth(22, 14 * 256); sheet.setColumnWidth(23, 15 * 256); sheet.setColumnWidth(24, 15 * 256); //6. 建立標題行 HSSFRow r0 = sheet.createRow(0); HSSFCell c0 = r0.createCell(0); c0.setCellValue("編號"); c0.setCellStyle(headerStyle); HSSFCell c1 = r0.createCell(1); c1.setCellStyle(headerStyle); c1.setCellValue("姓名"); HSSFCell c2 = r0.createCell(2); c2.setCellStyle(headerStyle); c2.setCellValue("工號"); HSSFCell c3 = r0.createCell(3); c3.setCellStyle(headerStyle); c3.setCellValue("性別"); HSSFCell c4 = r0.createCell(4); c4.setCellStyle(headerStyle); c4.setCellValue("出生日期"); HSSFCell c5 = r0.createCell(5); c5.setCellStyle(headerStyle); c5.setCellValue("身份證號碼"); HSSFCell c6 = r0.createCell(6); c6.setCellStyle(headerStyle); c6.setCellValue("婚姻狀況"); HSSFCell c7 = r0.createCell(7); c7.setCellStyle(headerStyle); c7.setCellValue("民族"); HSSFCell c8 = r0.createCell(8); c8.setCellStyle(headerStyle); c8.setCellValue("籍貫"); HSSFCell c9 = r0.createCell(9); c9.setCellStyle(headerStyle); c9.setCellValue("政治面貌"); HSSFCell c10 = r0.createCell(10); c10.setCellStyle(headerStyle); c10.setCellValue("電話號碼"); HSSFCell c11 = r0.createCell(11); c11.setCellStyle(headerStyle); c11.setCellValue("聯絡地址"); HSSFCell c12 = r0.createCell(12); c12.setCellStyle(headerStyle); c12.setCellValue("所屬部門"); HSSFCell c13 = r0.createCell(13); c13.setCellStyle(headerStyle); c13.setCellValue("職稱"); HSSFCell c14 = r0.createCell(14); c14.setCellStyle(headerStyle); c14.setCellValue("職位"); HSSFCell c15 = r0.createCell(15); c15.setCellStyle(headerStyle); c15.setCellValue("聘用形式"); HSSFCell c16 = r0.createCell(16); c16.setCellStyle(headerStyle); c16.setCellValue("最高學歷"); HSSFCell c17 = r0.createCell(17); c17.setCellStyle(headerStyle); c17.setCellValue("專業"); HSSFCell c18 = r0.createCell(18); c18.setCellStyle(headerStyle); c18.setCellValue("畢業院校"); HSSFCell c19 = r0.createCell(19); c19.setCellStyle(headerStyle); c19.setCellValue("入職日期"); HSSFCell c20 = r0.createCell(20); c20.setCellStyle(headerStyle); c20.setCellValue("在職狀態"); HSSFCell c21 = r0.createCell(21); c21.setCellStyle(headerStyle); c21.setCellValue("郵箱"); HSSFCell c22 = r0.createCell(22); c22.setCellStyle(headerStyle); c22.setCellValue("合同期限(年)"); HSSFCell c23 = r0.createCell(23); c23.setCellStyle(headerStyle); c23.setCellValue("合同起始日期"); HSSFCell c24 = r0.createCell(24); c24.setCellStyle(headerStyle); c24.setCellValue("合同終止日期"); for (int i = 0; i < list.size(); i++) { Employee emp = list.get(i); HSSFRow row = sheet.createRow(i + 1); row.createCell(0).setCellValue(emp.getId()); row.createCell(1).setCellValue(emp.getName()); row.createCell(2).setCellValue(emp.getWorkid()); row.createCell(3).setCellValue(emp.getGender()); HSSFCell cell4 = row.createCell(4); cell4.setCellStyle(dateCellStyle); cell4.setCellValue(emp.getBirthday()); row.createCell(5).setCellValue(emp.getIdcard()); row.createCell(6).setCellValue(emp.getWedlock()); row.createCell(7).setCellValue(emp.getNation().getName()); row.createCell(8).setCellValue(emp.getNativeplace()); row.createCell(9).setCellValue(emp.getPoliticsstatus().getName()); row.createCell(10).setCellValue(emp.getPhone()); row.createCell(11).setCellValue(emp.getAddress()); row.createCell(12).setCellValue(emp.getDepartment().getName()); row.createCell(13).setCellValue(emp.getJoblevel().getName()); row.createCell(14).setCellValue(emp.getPosition().getName()); row.createCell(15).setCellValue(emp.getEngageform()); row.createCell(16).setCellValue(emp.getTiptopdegree()); row.createCell(17).setCellValue(emp.getSpecialty()); row.createCell(18).setCellValue(emp.getSchool()); HSSFCell cell19 = row.createCell(19); cell19.setCellStyle(dateCellStyle); cell19.setCellValue(emp.getBegindate()); row.createCell(20).setCellValue(emp.getWorkstate()); row.createCell(21).setCellValue(emp.getEmail()); row.createCell(22).setCellValue(emp.getContractterm()); HSSFCell cell23 = row.createCell(23); cell23.setCellStyle(dateCellStyle); cell23.setCellValue(emp.getBegincontract()); HSSFCell cell24 = row.createCell(24); cell24.setCellStyle(dateCellStyle); cell24.setCellValue(emp.getEndcontract()); HSSFCell cell25 = row.createCell(25); cell25.setCellStyle(dateCellStyle); cell25.setCellValue(emp.getConversiontime()); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); HttpHeaders headers = new HttpHeaders(); try { headers.setContentDispositionFormData("attachment", new String("員工表.xls".getBytes("UTF-8"), "ISO-8859-1")); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); workbook.write(baos); } catch (IOException e) { e.printStackTrace(); } return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED); }
匯入
兩大步
- 檔案上傳
- 檔案解析
前後端檔案上傳
這裡用第二種方式
<el-upload //是否顯示上傳檔名 false為禁止 :show-file-list="false" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" //上傳檔案時是否禁止其它檔案上傳 :disabled="importDataDisabled" style="display: inline-flex;margin-right: 8px" //上傳路徑 action="/employee/basic/import"> <el-button :disabled="importDataDisabled" type="success" :icon="importDataBtnIcon"> {{importDataBtnText}} </el-button> </el-upload> <el-button type="success" @click="exportData" icon="el-icon-download"> 匯出資料 </el-button> data() { return { importDataBtnText: '匯入資料', importDataBtnIcon: 'el-icon-upload2', importDataDisabled: false }, methods: { onError(err, file, fileList) { this.importDataBtnText = '匯入資料'; this.importDataBtnIcon = 'el-icon-upload2'; this.importDataDisabled = false; }, onSuccess(response, file, fileList) { this.importDataBtnText = '匯入資料'; this.importDataBtnIcon = 'el-icon-upload2'; this.importDataDisabled = false; this.initEmps(); }, beforeUpload() { this.importDataBtnText = '正在匯入'; this.importDataBtnIcon = 'el-icon-loading'; //正在匯入時,設定importDataDisabled為true,禁止其它檔案上傳 this.importDataDisabled = true; }, exportData() { //匯出路徑並載入到父框架 window.open('/employee/basic/export', '_parent'); } }
Controller
@GetMapping("/export")
public ResponseEntity<byte[]> exportData() {
List<Employee> list = (List<Employee>) employeeService.getEmployeeByPage(null, null, null,null).getData();
return POIUtils.employee2Excel(list);
}
@PostMapping("/import")
public RespBean importData(MultipartFile file) throws IOException {
//解析上傳的檔案 將其中的職位名稱等含有中文欄位的轉化為資料庫ID
List<Emloyee> list = POIUtils.excel2Employee(file, nationService.getAllNations(), politicsstatusService.getAllPoliticsstatus(),
departmentService.getAllDepartmentsWithOutChildren(), positionService.getAllPositions(), jobLevelService.getAllJobLevels());
if (employeeService.addEmps(list) == list.size()) {
return RespBean.ok("上傳成功");
}
return RespBean.error("上傳失敗");
}
Excel解析
//匯入
public static List<Employee> excel2Employee(MultipartFile file, List<Nation> allNations,
List<Politicsstatus> allPoliticsstatus, List<Department> allDepartments, List<Position> allPositions, List<Joblevel> allJobLevels) {
List<Employee> list = new ArrayList<>();
Employee employee = null;
try {
//1. 建立一個 workbook 物件
HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
//2. 獲取 workbook 中表單的數量
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
//3. 獲取表單
HSSFSheet sheet = workbook.getSheetAt(i);
//4. 獲取表單中的行數
int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
for (int j = 0; j < physicalNumberOfRows; j++) {
//5. 跳過標題行
if (j == 0) {
continue;//跳過標題行
}
//6. 獲取行
HSSFRow row = sheet.getRow(j);
if (row == null) {
continue;//防止資料中間有空行
}
//7. 獲取列數
int physicalNumberOfCells = row.getPhysicalNumberOfCells();
employee = new Employee();
for (int k = 0; k < physicalNumberOfCells; k++) {
HSSFCell cell = row.getCell(k);
switch (cell.getCellType()) {
case STRING:
String cellValue = cell.getStringCellValue();
switch (k) {
case 1:
employee.setName(cellValue);
break;
case 2:
employee.setWorkid(cellValue);
break;
case 3:
employee.setGender(cellValue);
break;
case 5:
employee.setIdcard(cellValue);
break;
case 6:
employee.setWedlock(cellValue);
break;
case 7:
int nationIndex =
allNations.indexOf(new Nation(cellValue));
employee.setNationid(allNations.get(nationIndex).getId());
break;
case 8:
employee.setNativeplace(cellValue);
break;
case 9:
int politicstatusIndex = allPoliticsstatus.indexOf(new Politicsstatus(cellValue));
employee.setPoliticid(allPoliticsstatus.get(politicstatusIndex).getId());
break;
case 10:
employee.setPhone(cellValue);
break;
case 11:
employee.setAddress(cellValue);
break;
case 12:
int departmentIndex = allDepartments.indexOf(new Department(cellValue));
employee.setDepartmentid(allDepartments.get(departmentIndex).getId());
break;
case 13:
int jobLevelIndex =
allJobLevels.indexOf(new Joblevel(cellValue));
employee.setJoblevelid(allJobLevels.get(jobLevelIndex).getId());
break;
case 14:
int positionIndex = allPositions.indexOf(new Position(cellValue));
employee.setPosid(allPositions.get(positionIndex).getId());
break;
case 15:
employee.setEngageform(cellValue);
break;
case 16:
employee.setTiptopdegree(cellValue);
break;
case 17:
employee.setSpecialty(cellValue);
break;
case 18:
employee.setSchool(cellValue);
break;
case 20:
employee.setWorkstate(cellValue);
break;
case 21:
employee.setEmail(cellValue);
break;
}
break;
default: {
switch (k) {
case 4:
employee.setBirthday(cell.getDateCellValue());
break;
case 19:
employee.setBegindate(cell.getDateCellValue());
break;
case 23:
employee.setBegincontract(cell.getDateCellValue());
break;
case 24:
employee.setEndcontract(cell.getDateCellValue());
break;
case 22:
employee.setContractterm(cell.getNumericCellValue());
break;
case 25:
employee.setConversiontime(cell.getDateCellValue());
break;
}
}
break;
}
}
list.add(employee);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
因為表中的資料nation等是漢字,需要將它轉換為nationId,要根據名字查詢nationId,那麼可以只根據name重寫類的equals和hashcode方法
controller
@PostMapping("/import")
public RespBean importData(MultipartFile file) throws IOException{
//解析上傳的檔案 將其中的職位名稱等含有中文欄位的轉化為資料庫ID
List<Employee> list = POIUtils.excel2Employee(file, nationService.getAllNation(),
politicsstatusService.getAllPoliticsstatus(),
departmentService.getAllDepartmentsWithOutChildren(),
positionService.getAllPositons(),
jobLevelService.getAllJobLevels());
if (employeeService.addEmps(list) == list.size()) {
return RespBean.ok("上傳成功");
}
System.out.println(list);
return RespBean.error("上傳失敗");
}
xml
<insert id="addEmps" parameterType="com.qwl.vhr.model.Employee">
insert into employee ( name, gender,
birthday, idCard, wedlock, nationId,
nativePlace, politicId, email,
phone, address, departmentId,
jobLevelId, posId, engageForm,
tiptopDegree, specialty, school,
beginDate, workState, workID,
contractTerm, conversionTime, notWorkDate,
beginContract, endContract, workAge
)
values
<foreach collection="list" separator="," item="emp">
(#{emp.name,jdbcType=VARCHAR}, #{emp.gender,jdbcType=CHAR},
#{emp.birthday,jdbcType=DATE}, #{emp.idcard,jdbcType=CHAR}, #{emp.wedlock,jdbcType=CHAR}, #{emp.nationid,jdbcType=INTEGER},
#{emp.nativeplace,jdbcType=VARCHAR}, #{emp.politicid,jdbcType=INTEGER}, #{emp.email,jdbcType=VARCHAR},
#{emp.phone,jdbcType=VARCHAR}, #{emp.address,jdbcType=VARCHAR}, #{emp.departmentid,jdbcType=INTEGER},
#{emp.joblevelid,jdbcType=INTEGER}, #{emp.posid,jdbcType=INTEGER}, #{emp.engageform,jdbcType=VARCHAR},
#{emp.tiptopdegree,jdbcType=CHAR}, #{emp.specialty,jdbcType=VARCHAR}, #{emp.school,jdbcType=VARCHAR},
#{emp.begindate,jdbcType=DATE}, #{emp.workstate,jdbcType=CHAR}, #{emp.workid,jdbcType=CHAR},
#{emp.contractterm,jdbcType=DOUBLE}, #{emp.conversiontime,jdbcType=DATE}, #{emp.notworkdate,jdbcType=DATE},
#{emp.begincontract,jdbcType=DATE}, #{emp.endcontract,jdbcType=DATE}, #{emp.workage,jdbcType=INTEGER}
)
</foreach>