Excel导出接口
/*** 信息资源导出*/@PostMapping({ "/export" })@PreAuthorize("@pms.hasPermission('dna_resrc_export')")@ApiOperation(value = "信息资源导出", notes = "信息资源导出", httpMethod = "POST")public void exportExcel(@RequestBody DnaDirResrcPageDTO dto, HttpServletRequest request,HttpServletResponse response) throws Exception {//新增pageWithInput方法,直接获取本身加关联,并按照解析的方式赋值List<DnaDirResrc> list = dnaResrcService.getVOList(dto);//目录List<DnaDirResrcPOI> poiList = new ArrayList<DnaDirResrcPOI>();//信息项List<DnaDirElementPOI> dnaDirElementPOIS = new ArrayList<DnaDirElementPOI>();//设置返回头
// setResponse(response, "数据资源目录");response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");// 这里URLEncoder.encode可以防止中文乱码String fileName = URLEncoder.encode("template", "UTF-8");response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");//新建ExcelWriterExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();//获取sheet0对象WriteSheet mainSheet = EasyExcel.writerSheet(0, "数据目录").head(DnaDirResrcPOI.class)//设置拦截器或自定义样式.registerWriteHandler(getStyleStrategy()).build();//向sheet0写入数据 传入空list这样只导出表头excelWriter.write(poiList, mainSheet);//获取sheet1对象WriteSheet detailSheet = EasyExcel.writerSheet(1, "信息项").head(DnaDirElementPOI.class)//设置拦截器或自定义样式.registerWriteHandler(getStyleStrategy()).build();//向sheet1写入数据 传入空list这样只导出表头excelWriter.write(dnaDirElementPOIS, detailSheet);//关闭流excelWriter.finish();}
去除默认表头样式及设置内容居中
//设置样式 去除默认表头样式及设置内容居中public static HorizontalCellStyleStrategy getStyleStrategy(){//内容样式策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//垂直居中,水平居中contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);contentWriteCellStyle.setBorderTop(BorderStyle.THIN);contentWriteCellStyle.setBorderRight(BorderStyle.THIN);contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);//设置 自动换行contentWriteCellStyle.setWrapped(true);// 字体策略WriteFont contentWriteFont = new WriteFont();// 字体大小contentWriteFont.setFontHeightInPoints((short) 12);contentWriteCellStyle.setWriteFont(contentWriteFont);//头策略使用默认WriteCellStyle headWriteCellStyle = new WriteCellStyle();headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);}