Spring Boot Excel文件导出下载实现代码
SpringBootExcel文件导出
目标:
实现Excel文件的直接导出下载,后续开发不需要开发很多代码,直接继承已经写好的代码,增加一个Xml配置就可以直接导出。
实现:
1、抽象类BaseExcelView继承webmvc的 AbstractXlsxStreamingView抽象类,AbstractXlsxStreamingView是webmvc继承了最顶层View接口,是可以直接大量数据导出的不会造成内存泄漏问题,即SXSSFWorkbook解决了内存问题,导出只支持xlsx类型文件。
抽象类代码BaseExcelView:
publicabstractclassBaseExcelViewextendsAbstractXlsxStreamingView{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(BaseExcelView.class); /** *获取导出文件名 * *@return */ abstractprotectedStringgetFileName(); /** *获取表单名称 * *@return */ abstractprotectedStringgetSheetName(); /** *获取标题栏名称 * *@return */ abstractprotectedString[]getTitles(); /** *获取列宽 * *@return */ abstractprotectedshort[]getColumnWidths(); /** *构造内容单元格 * *@paramsheet */ abstractprotectedvoidbuildContentCells(Sheetsheet); @Override protectedvoidbuildExcelDocument( Mapmodel,Workbookworkbook,HttpServletRequestrequest,HttpServletResponseresponse) throwsException{ //构造标题单元格SXSSFWorkbook Sheetsheet=buildTitleCells(workbook); //构造内容单元格 buildContentCells(sheet); //设置响应头 setResponseHead(request,response); } /** *设置响应头 * *@paramresponse *@throwsIOException */ protectedvoidsetResponseHead(HttpServletRequestrequest, HttpServletResponseresponse)throwsIOException{ //文件名 StringfileName=getFileName(); StringuserAgent=request.getHeader("user-agent").toLowerCase(); logger.info("客户端请求头内容:"); logger.info("user-agent\t值:{}",userAgent); if(userAgent!=null){ if(userAgent.contains("firefox")){ //firefox有默认的备用字符集是西欧字符集 fileName=newString(fileName.getBytes("UTF-8"),"ISO8859-1"); }elseif(userAgent.contains("webkit")&&(userAgent.contains("chrome")||userAgent.contains("safari"))){ //webkit核心的浏览器,主流的有chrome,safari,360 fileName=newString(fileName.getBytes("UTF-8"),"ISO8859-1"); }else{ //新老版本的IE都可直接用URL编码工具编码后输出正确的名称,无乱码 fileName=URLEncoder.encode(fileName,"UTF-8"); } } //响应头信息 response.setCharacterEncoding("UTF-8"); response.setContentType("application/ms-excel;charset=UTF-8"); response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx"); } /** *构造标题单元格 * *@param *@return */ protectedSheetbuildTitleCells(Workbookworkbook){ //表单名称 StringsheetName=getSheetName(); //标题名称 String[]titles=getTitles(); //列宽 short[]colWidths=getColumnWidths(); //创建表格 Sheetsheet=workbook.createSheet(sheetName); //标题单元格样式 CellStyletitleStyle=getHeadStyle(workbook); //默认内容单元格样式 CellStylecontentStyle=getBodyStyle(workbook); //标题行 RowtitleRow=sheet.createRow(0); //创建标题行单元格 for(inti=0;i Excel导出实现1:可以直接继承BaseExcelView 实现定义的方法eg:
publicclassCheckExcelViewextendsBaseExcelView{ privateListvo; publicCheckExcelView(List vo){ this.vo=vo; } @Override protectedStringgetFileName(){ Stringtime=DateUtils.getLocalFullDateTime14(); return"导出文件"+time; } @Override protectedStringgetSheetName(){ return"报表"; } @Override protectedString[]getTitles(){ returnnewString[]{"申请时间"}; } @Override protectedshort[]getColumnWidths(){ returnnewshort[]{20}; } @Override protectedvoidbuildContentCells(Sheetsheet){ DecimalFormatdf=newDecimalFormat("0.00"); introwNum=1; for(To:vO){ Rowcrow=sheet.createRow(rowNum++); crow.createCell(0).setCellValue(o.getApplicationDate())); } } } 导出实现2:XML配置导出
1、需要定义XML的配置export-config.xml
2、XMl解析配置
@Root publicclassExport{ @ElementList(entry="table",inline=true) privateListtable; publicList
getTable(){ returntable; } publicvoidsetTable(List
table){ this.table=table; } publicstaticclassTable{ @Attribute privateStringid; @Attribute privateStringname; @ElementList(entry="column") privateList
columns; publicStringgetId(){ returnid; } publicvoidsetId(Stringid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicList getColumns(){ returncolumns; } publicvoidsetColumns(List columns){ this.columns=columns; } } publicstaticclassColumn{ @Attribute privateStringid; @Attribute privateStringname; @Attribute privateshortwidth; @Attribute(required=false) privateStringmapping; publicStringgetId(){ returnid; } publicvoidsetId(Stringid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicStringgetMapping(){ returnmapping; } publicvoidsetMapping(Stringmapping){ this.mapping=mapping; } publicshortgetWidth(){ returnwidth; } publicvoidsetWidth(shortwidth){ this.width=width; } } } 3、解析XMl方法配置
@Service publicclassIExportService{ privateExporttables; privateMaptableMap; @SuppressWarnings("rawtypes") @PostConstruct publicvoidinit()throwsException{ InputStreaminputStream=this.getClass().getClassLoader().getResourceAsStream("export-config.xml"); Serializerserializer=newPersister(); tables=serializer.read(Export.class,inputStream); tableMap=newHashMap<>(); for(Export.Tabletable:tables.getTable()){ tableMap.put(table.getId(),table); } } publicExport.TablegetTable(Stringkey){ returntableMap.get(key); } } 4、导出基础 ExcelExportView代码实现
publicclassExcelExportViewextendsBaseExcelView{ privateString[]titles; privateshort[]columnWidths; List