更多的easyPOI資源的網在easypoi的官網。java
1 在pom.xml中添加依賴web
<dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.0.3</version> </dependency>
2 工具類spring
package com.hhsj.tools.excelUtils; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; public class ExcelUtils { /** * excel 導出 * * @param list 數據 * @param title 標題 * @param sheetName sheet名稱 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param isCreateHeader 是否建立表頭 * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException { ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } /** * excel 導出 * * @param list 數據 * @param title 標題 * @param sheetName sheet名稱 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException { defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF)); } /** * excel 導出 * * @param list 數據 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response * @param exportParams 導出參數 */ public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException { defaultExport(list, pojoClass, fileName, response, exportParams); } /** * excel 導出 * * @param list 數據 * @param fileName 文件名稱 * @param response */ public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { defaultExport(list, fileName, response); } /** * 默認的 excel 導出 * * @param list 數據 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response * @param exportParams 導出參數 */ private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); downLoadExcel(fileName, response, workbook); } /** * 默認的 excel 導出 * * @param list 數據 * @param fileName 文件名稱 * @param response */ private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); downLoadExcel(fileName, response, workbook); } /** * 下載 * * @param fileName 文件名稱 * @param response * @param workbook excel數據 */ private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8") + "." + ExcelTypeEnum.XLSX.getValue()); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param filePath excel文件路徑 * @param titleRows 標題行 * @param headerRows 表頭行 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException { if (StringUtils.isBlank(filePath)) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); params.setNeedSave(true); params.setSaveUrl("/excel/"); try { return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); } catch (NoSuchElementException e) { throw new IOException("模板不能爲空"); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param file excel文件 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException { return importExcel(file, 1, 1, pojoClass); } /** * excel 導入 * * @param file excel文件 * @param titleRows 標題行 * @param headerRows 表頭行 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException { return importExcel(file, titleRows, headerRows, false, pojoClass); } /** * excel 導入 * * @param file 上傳的文件 * @param titleRows 標題行 * @param headerRows 表頭行 * @param needVerfiy 是否檢驗excel內容 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException { if (file == null) { return null; } try { return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param inputStream 文件輸入流 * @param titleRows 標題行 * @param headerRows 表頭行 * @param needVerfiy 是否檢驗excel內容 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException { if (inputStream == null) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); params.setSaveUrl("/excel/"); params.setNeedSave(true); params.setNeedVerfiy(needVerfiy); try { return ExcelImportUtil.importExcel(inputStream, pojoClass, params); } catch (NoSuchElementException e) { throw new IOException("excel文件不能爲空"); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * Excel 類型枚舉 */ enum ExcelTypeEnum { XLS("xls"), XLSX("xlsx"); private String value; ExcelTypeEnum(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
3 實體類apache
package com.hhsj.entity.salaryWorkAttendance; import cn.afterturn.easypoi.excel.annotation.Excel; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.Date; @Data @Entity @EqualsAndHashCode(callSuper = false) @Table(name = "c_work_attendance") @EntityListeners(AuditingEntityListener.class) @ApiModel(value = "WorkAttendance" ,description = "考勤信息表") public class WorkAttendance { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") private String id; private String corpId; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @CreatedDate private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @LastModifiedDate private Date updateTime; @Excel(name = "員工姓名",orderNum = "0",width = 15) @ApiModelProperty(value = "員工姓名") private String employeeName; @Excel(name = "崗位",orderNum = "1",width = 15) @ApiModelProperty(value = "崗位") private String post; @Excel(name = "對應器械",orderNum = "2",width = 15) @ApiModelProperty(value = "對應器械") private String correspondingApparatus; @Excel(name = "關聯項目",orderNum = "3",width = 15) @ApiModelProperty(value = "關聯項目") private String relatedItems; @Excel(name = "裝卸點選擇",orderNum = "4",width = 15) @ApiModelProperty(value = "裝卸點選擇") private String pointChoice; @Excel(name = "考勤時間",orderNum = "5",format = "yyyy-MM-dd HH:mm:ss",width = 25) @ApiModelProperty(value = "考勤時間") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date attendanceTime; @Excel(name = "考勤類型",orderNum = "7",width = 15) @ApiModelProperty(value = "考勤類型") private String attendanceType; @Excel(name = "位置",orderNum = "8",width = 15) @ApiModelProperty(value = "位置") private String position; @ApiModelProperty(value = "現場照片") private String img; }
4 具體操做app
package com.hhsj.service.salaryWorkAttendance.impl; import com.hhsj.common.Result; import com.hhsj.entity.salaryWorkAttendance.WorkAttendance; import com.hhsj.exception.NormalException; import com.hhsj.repository.salaryWorkAttendance.WorkAttendanceRepository; import com.hhsj.request.salaryWorkAttendance.WorkAttendanceRequest; import com.hhsj.service.salaryWorkAttendance.IWorkAttendanceService; import com.hhsj.token.TokenUtils; import com.hhsj.tools.excelUtils.ExcelUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; @Service public class WorkAttendanceServiceImpl implements IWorkAttendanceService { @Autowired private WorkAttendanceRepository workAttendanceRepository; @Autowired private TokenUtils tokenUtils; @Override @Transactional(readOnly = false,rollbackFor = Exception.class) public Result<String> workAttendanceImport(MultipartFile file) { String corpId = tokenUtils.getCurrentCorpId(); //獲取上傳文件的名稱 String fileName = file.getOriginalFilename(); if (!Objects.requireNonNull(fileName).matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { throw new NormalException("上傳文件格式不正確"); } try { List<WorkAttendance> attendances = ExcelUtils.importExcel(file,WorkAttendance.class); if (attendances != null && attendances.size() != 0){ for (WorkAttendance attendance : attendances) { attendance.setCorpId(corpId); workAttendanceRepository.save(attendance); } } }catch (Exception e){ throw new NormalException("上傳失敗"); } return Result.<String>builder().success().message("上傳成功").build(); } @Override public Result<String> workAttendanceExport(HttpServletResponse response) { WorkAttendance workAttendance = new WorkAttendance(); workAttendance.setAttendanceTime(new Date()); List<WorkAttendance> list = new ArrayList<>(); list.add(workAttendance); try { ExcelUtils.exportExcel(list,"考勤模板","考勤模板",WorkAttendance.class,"kaoqin",response); } catch (IOException e) { throw new NormalException("模板下載失敗"); } return Result.<String>builder().success().message("導出成功").build(); } }