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; } }