SpringBoot + easypoi 自定义模板导出excel

一.pom文件添加easypoi依赖包

SpringBoot + easypoi 自定义模板导出excel_第1张图片

二.编写后台方法

@GetMapping("/exportSetlCont")
    @ApiOperation(value = "导出", httpMethod = "GET")
    public void exportSetlCont(DrgSetlCont drgSetlCont,HttpServletRequest request,HttpServletResponse response){
        try {
            // 查询后台数据
            List list = setlDataService.queryDrgSetlContData(drgSetlCont);
            //文件名
            String fileName = drgSetlCont.getDate()+drgSetlCont.getFileName();
            //TemplateExportParams param = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\模板.xlsx", true);
            // 获取打成jar包后静态文件在classpath目录下得方法。不然获取不到模板文件,导致导出文件损坏。
            TemplateExportParams params = new TemplateExportParams();
            Workbook workbook = WorkbookFactory.create(getClass().getClassLoader().getResourceAsStream("static/static/template/模板.xlsx"));
            params.setTemplateWb(workbook);
            params.setStyle(ExcelStyleType.BORDER.getClazz());
            Map map = new HashMap();
            map.put("date",drgSetlCont.getDate());
            map.put("dataList", list);
            Workbook book = ExcelExportUtil.exportExcel(params, map);
            //下载方法
            export(response, book, fileName);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
/**
     * export导出请求头设置
     *
     * @param response
     * @param workbook
     * @param fileName
     * @throws Exception
     */
    private static void export(HttpServletResponse response, Workbook workbook, String fileName) throws Exception {
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName+".xlsx", "UTF-8"));
        ServletOutputStream outStream = null;
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } finally {
            outStream.close();
        }

    }

模板文件路径

SpringBoot + easypoi 自定义模板导出excel_第2张图片

模板取值

SpringBoot + easypoi 自定义模板导出excel_第3张图片

前端

自己写吧 啊哈哈哈!!!

你可能感兴趣的:(java)