easypoi實現excel文件上傳
1、導入excel文件內容實體類:pojo類
@Data public class RosterVO implements Serializable { private static final long serialVersionUID = -4539164487279140234L;
//導入文件模板頭校驗 public static final String[] MUST_FILL = new String[]{"工號", "員工姓名(必填)", "手機號碼(必填)", "性別", "證件類型(必填)", "身份證號碼(必填)", "開戶行(必填)", "銀行卡號(必填)", "工種"}; private Long rsId; @Excel(name = "工號", orderNum = "1", width = 10) private String rsJobNumber; @Excel(name = "員工姓名(必填)", orderNum = "2", width = 15) private String rsContractor; @Excel(name = "手機號碼(必填)", orderNum = "3", width = 13) private String rsMobile; @Excel(name = "性別", orderNum = "4", width = 10) private String rsSex; @Excel(name = "證件類型(必填)", orderNum = "5", width = 15) private String idCardType; private Integer rsIdCardType; @Excel(name = "身份證號碼(必填)", orderNum = "6", width = 20) private String rsIdCard; @Excel(name = "開戶行(必填)", orderNum = "7", width = 15) private String rsBankName; @Excel(name = "銀行卡號(必填)", orderNum = "8", width = 22) private String rsBankAccount; private Integer rsContractualStatus; @Excel(name = "工種", orderNum = "9", width = 10) private String rsTypeOfWork; }
2、導入文件具體實現:service層
public Object importExcel(MultipartFile file, Integer sccId, HttpServletResponse response, HttpServletRequest request) throws Exception { //此處判斷文件大小不能為0 if (file.getSize() == 0) { return R.error(ConstantsEnum.FILE_NOT_NULL.getValue(), "excel內容不能為空"); } // 根據file得到Workbook,主要是要根據這個對象獲取,傳過來的excel有幾個sheet頁 Workbook hssfWorkbook = ExcelUtil.getWorkBook(file); int numSheet = hssfWorkbook.getNumberOfSheets(); System.out.println(numSheet + "numsheet數量"); if (numSheet > 1) { return R.error(ConstantsEnum.FILE_ONLY_ONESHEET.getValue(), "excel文件只能有一個sheet"); } ImportParams params = new ImportParams(); params.setTitleRows(0); // 表格標題行 params.setHeadRows(1); // 表格表頭行 params.setSheetNum(numSheet); params.setNeedVerify(true); // 是否對上傳的表格進行校驗 params.setImportFields(RosterVO.MUST_FILL); //判斷導入的excel中的表頭字段是否合法,非空驗證 List<RosterVO> successList = new ArrayList<RosterVO>(); List<RosterVO> failList = new ArrayList<RosterVO>(); //此處如果導入文件為空(文件表頭也沒有),會拋NoSuchElementException異常,需要處理攔截 List<RosterVO> list = ExcelImportUtil.importExcel(file.getInputStream(), RosterVO.class, params); } for (RosterVO roster : list) { //處理導入數據 } //業務邏輯根據實際情況處理 }
3、exce文件導入導出工具類:(此篇只用看getWorkBook方法即可)
package io.renren.common.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.text.SimpleDateFormat;import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; 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; /** * @program: ivvdata-security * @description: 文件導入導出工具 * @author: HYJ * @create: 2019-09-25 14:16 */ public class ExcelUtil { /** * 得到Workbook對象 * * @param file * @return * @throws IOException */ public static Workbook getWorkBook(MultipartFile file) throws IOException { // 這樣寫 excel 能兼容03和07 InputStream is = file.getInputStream(); Workbook hssfWorkbook = null; try { hssfWorkbook = new HSSFWorkbook(is); } catch (Exception ex) { is = file.getInputStream(); hssfWorkbook = new XSSFWorkbook(is); } return hssfWorkbook; } /** * 需要模板的根據map集合獲取excel(workbook)導出 * @param fileName * @param workbook * @param request * @param response * @throws IOException */ public static void exportExcel(String fileName, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws IOException { response.reset(); response.setContentType("multipart/form-data"); //解決下載時中文文件名亂碼和下載時因為路徑中包含中文文件名亂碼,提示找不到文件 String userAgent = request.getHeader("User-Agent"); // 針對IE或者以IE為內核的瀏覽器: if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { fileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else { // 非IE瀏覽器的處理: fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); } // 判斷excel文件類型,下載獲取到的模板並重新命名 if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) { response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xls"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xlsx"); } // 輸出流 workbook.write(response.getOutputStream()); } /** * 不需要模板導出excel的注解方式 * @param exportParams * @param fileName * @param pojoClass * @param list * @param response * @throws IOException */ public static void exportExcel(ExportParams exportParams, String fileName, Class<?> pojoClass, List<?> list, HttpServletResponse response) throws IOException { // 生成workbook並導出 Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); response.reset(); // 清空輸出流 response.setContentType("multipart/form-data"); System.out.println(workbook.getClass().getSimpleName()); // 下載excel並重新命名並判斷是xlsx格式還是xls格式 if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) { response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xls"); } else { response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1") + ".xlsx"); } // 輸出流 workbook.write(response.getOutputStream()); } /** * 不需要模板導出excel的注解方式,上傳到服務器,返回的是下載路徑 * @param exportParams * @param fileName * @param pojoClass * @param list * @param response * @throws IOException */ public static String exportExcel(ExportParams exportParams, String fileName, Class<?> pojoClass, List<?> list, HttpServletResponse response, HttpServletRequest request) throws IOException { // 生成workbook並導出 Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); // 定義上傳文件存放的路徑 String path1 = request.getSession().getServletContext().getRealPath("/temporaryUploadExcel/"); // 定義文件在上傳路徑中的文件夾名稱 File folder = new File(path1); // 檢測folder是否是文件夾,不是就創建 if (!folder.isDirectory()) { folder.mkdirs(); } // 下載excel並重新命名並判斷是xlsx格式還是xls格式 if (workbook.getClass().getSimpleName().equals("HSSFWorkbook")) { String excelName = fileName + ".xls"; // 將workbook文件寫入流並上傳至服務器 path1:上傳文件存放路徑 excel:文件夾名稱 excelName:文件名 FileOutputStream fileOutputStream = new FileOutputStream(path1+ excelName); workbook.write(fileOutputStream); String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/ivvdata-admin" + "/temporaryUploadExcel/" + excelName; return path; } else { String excelName = fileName + ".xlsx"; // 將文件流寫入文件並上傳至服務器 path1:上傳文件存放路徑 excel:文件夾名稱 excelName:文件名 FileOutputStream fileOutputStream = new FileOutputStream(path1 + excelName); workbook.write(fileOutputStream); String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/ivvdata-admin" + "/temporaryUploadExcel/" + excelName; System.out.println("獲取路徑" + path); return path; } } /* * 下方所有方法根據自己情況選擇加工使用,和上面加工過的方法存在一致 */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) { ExportParams exportParams = new ExportParams(title, sheetName); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) { defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); } public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { defaultExport(list, fileName, response); } private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) { Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); if (workbook != null); downLoadExcel(fileName, response, workbook); } private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { // throw new NormalException(e.getMessage()); } } private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); if (workbook != null); downLoadExcel(fileName, response, workbook); } public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (StringUtils.isBlank(filePath)) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); } catch (NoSuchElementException e) { // throw new NormalException("模板不能為空"); } catch (Exception e) { e.printStackTrace(); // throw new NormalException(e.getMessage()); } return list; } public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) { if (file == null) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); List<T> list = null; try { list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); } catch (NoSuchElementException e) { // throw new NormalException("excel文件不能為空"); } catch (Exception e) { // throw new NormalException(e.getMessage()); System.out.println(e.getMessage()); } return list; } }
