easypoi導出excel文件
1、直接展示實現方法:controller層
@GetMapping("/downloadByRoster") public R downLoadTemplateByRoster(Integer sccId, HttpServletResponse response, HttpServletRequest request) throws Exception {// 獲取模板 String excelName = "xxxx年xx月制單模板xx批.xls"; TemplateExportParams params = new TemplateExportParams("excel/xxxx年xx月制單模板xx批.xls"); // 設置模板中的sheetName // params.setSheetName("支付明細表"); // 向模板中間設置 HashMap<String, Object> map = new HashMap<String, Object>(); List<Map<String, String>> listMap = new ArrayList<Map<String, String>>();
//此處數據根據項目情況獲得 List<RosterVO> list = rosterDao.findRosterByMobiles(sccId); for (RosterVO roster : list) { HashMap<String, String> lm = new HashMap<String, String>(); lm.put("pdContractor", roster.getRsContractor()); lm.put("pdIdCard", roster.getRsIdCard()); lm.put("pdBankName", roster.getRsBankName()); lm.put("pdBankAccount", roster.getRsBankAccount()); lm.put("pdMobile", roster.getRsMobile()); listMap.add(lm); } map.put("maplist", listMap); // 獲取excel Workbook workbook = ExcelExportUtil.exportExcel(params, map); ExcelUtil.exportExcel("excel", workbook, request, response);
2、excel導入導出工具類:此處只用看需要模板的根據map集合獲取excel(workbook)導出
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; } }
3、模板來源:工程下resources文件夾下新建的excel文件夾中
4、最重要的一點,模板到底該如何設置,參考http://doc.wupaas.com/docs/easypoi/easypoi-1c0u4mo8p4ro8中Excel模板版