SpringBoot快速集成jxls-poi(自定义模板,支持本地文件导出,在线文件导出)
在项目持续集成的过程中,有时候需要实现报表导出和文档导出,类似于excel中这种文档的导出,在要求不高的情况下,有人可能会考虑直接导出csv文件来简化导出过程。但是导出xlsx文件,其实过程相对更复杂。解决方案就是使用poi的jar包。使用源生的poi来操作表格,代码冗余,处理复杂,同时poi的相关联的依赖还会存在版本兼容问题。所以直接使用poi来实现表格导出,维护成本大,不易于拓展。
我们需要学会站在巨人的肩膀上解决问题,jxls-poi这个就很好解决这个excel表格导出的多样化的问题。类似jsp和thymealf的模板定义,使得表格导出变得简单可控。
不多BB上代码
1.引入关键依赖包
org.jxls jxls-poi 1.0.15 org.jxls jxls 2.4.6
这里只需要两个依赖便操作excel表格了。
2.定义模板文件
新建一个excel文件,后缀名为.xlsx,在resources目录下新增一个jxls的文件夹,把模板文件放在这个文件夹下,便于后续的spring-boot的集成。
3.导出工具类
/** *@authormachenike */ publicclassExcelUtils{ /*** *excel导出到response *@paramfileName导出文件名 *@paramtemplateFile模板文件地址 *@paramparams数据集合 *@paramresponseresponse */ publicstaticvoidexportExcel(StringfileName,InputStreamtemplateFile,Mapparams, HttpServletResponseresponse)throwsIOException{ response.reset(); response.setHeader("Accept-Ranges","bytes"); OutputStreamos=null; response.setHeader("Content-disposition",String.format("attachment;filename=\"%s\"",fileName)); response.setContentType("application/octet-stream;charset=UTF-8"); try{ os=response.getOutputStream(); exportExcel(templateFile,params,os); }catch(IOExceptione){ throwe; } } /** *导出excel到输出流中 *@paramtemplateFile模板文件 *@paramparams传入参数 *@paramos输出流 *@throwsIOException */ publicstaticvoidexportExcel(InputStreamtemplateFile,Map params,OutputStreamos)throwsIOException{ try{ Contextcontext=newContext(); Set keySet=params.keySet(); for(Stringkey:keySet){ //设置参数变量 context.putVar(key,params.get(key)); } Map myFunction=newHashMap<>(); myFunction.put("fun",newExcelUtils()); //启动新的jxls-api加载自定义方法 Transformertrans=TransformerFactory.createTransformer(templateFile,os); JexlExpressionEvaluatorevaluator=(JexlExpressionEvaluator)trans.getTransformationConfig().getExpressionEvaluator(); evaluator.getJexlEngine().setFunctions(myFunction); //载入模板、处理导出 AreaBuilderareaBuilder=newXlsCommentAreaBuilder(trans); ListareaList=areaBuilder.build(); areaList.get(0).applyAt(newCellRef("sheet1!A1"),context); trans.write(); }catch(IOExceptione){ throwe; }finally{ try{ if(os!=null){ os.flush(); os.close(); } if(templateFile!=null){ templateFile.close(); } }catch(IOExceptione){ throwe; } } } /** *格式化时间 */ publicObjectformatDate(Datedate){ if(date!=null){ SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); StringdateStr=sdf.format(date); returndateStr; } return"--"; } /** *设置超链接方法 */ publicWritableCellValuegetLink(Stringaddress,Stringtitle){ returnnewWritableHyperlink(address,title); } }
这个工具类中我定义两个导出用的方法
一个是直接是HttpServletResponse导出在线下载文件
一个使用输入流导出
同时模板中还支持方法传入。
4.定义导出服务类
全局配置jxls模板的基础路径
#jxls模板的基础路径 jxls.template.path:classpath:jxls/
定义服务接口
/** *excel用service */ publicinterfaceExcelService{ /** *导出excel,写入输出流中 *@paramtemplateFile *@paramparams *@paramos *@return */ booleangetExcel(StringtemplateFile,Mapparams,OutputStreamos); /** *导出excel,写入response中 *@paramtemplateFile *@paramfileName *@paramparams *@paramresponse *@return */ booleangetExcel(StringtemplateFile,StringfileName,Map params,HttpServletResponseresponse); /** *导出excel,写入文件中 *@paramtemplateFile *@paramparams *@paramoutputFile *@return */ booleangetExcel(StringtemplateFile,Map params,FileoutputFile); }
excel导出用服务实现类
/** *excel用serviceImpl */ @Service publicclassExcelServiceImpplimplementsExcelService{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(ExcelServiceImppl.class); /** *模板文件的基础路径 */ @Value("${jxls.template.path}") privateStringtemplatePath; @Override publicbooleangetExcel(StringtemplateFile,Mapparams,OutputStreamos){ FileInputStreaminputStream=null; try{ //获取模板文件的输入流 inputStream=newFileInputStream(ResourceUtils.getFile(templatePath+templateFile)); //导出文件到输出流 ExcelUtils.exportExcel(inputStream,params,os); }catch(IOExceptione){ logger.error("excelexporthaserror"+e); returnfalse; } returntrue; } @Override publicbooleangetExcel(StringtemplateFile,StringfileName,Map params,HttpServletResponseresponse){ FileInputStreaminputStream=null; try{ //获取模板文件的输入流 inputStream=newFileInputStream(ResourceUtils.getFile(templatePath+templateFile)); //导出文件到response ExcelUtils.exportExcel(fileName,inputStream,params,response); }catch(IOExceptione){ logger.error("excelexporthaserror"+e); returnfalse; } returntrue; } @Override publicbooleangetExcel(StringtemplateFile,Map params,FileoutputFile){ FileInputStreaminputStream=null; try{ //获取模板文件的输入流 inputStream=newFileInputStream(ResourceUtils.getFile(templatePath+templateFile)); FiledFile=outputFile.getParentFile(); //文件夹不存在时创建文件夹 if(dFile.isDirectory()){ if(!dFile.exists()){ dFile.mkdir(); } } //文件不存在时创建文件 if(!outputFile.exists()){ outputFile.createNewFile(); } //导出excel文件 ExcelUtils.exportExcel(inputStream,params,newFileOutputStream(outputFile)); }catch(IOExceptione){ logger.error("excelexporthaserror"+e); returnfalse; } returntrue; } }
如上,服务类提供了,三种导出的实现方法
- 导出excel写入response中
- 导出excel写入输出流中
- 导出excel写入文件中
这三种方法足以覆盖所有的业务需求
5.编辑jxls模板
这里为方便导出最好定义与模板匹配的实体类,便于数据的装载和导出
publicclassUserModel{ privateIntegerid; privateStringname; privateStringsex; privateIntegerage; privateStringremark; privateDatedate; privateStringlink; }
jx:each(items="list"var="item"lastCell="G3")
上面G3模板中迭代的结束位置,然后用类似EL表达式的方式填充到模板当中
jx:area(lastCell="G3")
模板编辑完成后保存即可,
6.代码测试使用
导出为本地文件
@SpringBootTest classBlogJxlsApplicationTests{ @Autowired ExcelServiceexcelService; @Test voidcontextLoads(){ Mapparams=newHashMap(); List list=newArrayList<>(); list.add(newUserModel(1,"test01","男",25,"tttttttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(2,"test02","男",20,"tttttttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(3,"test04","女",25,"ttttddddasdadatttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(4,"test08","男",20,"ttttttdasdatttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(5,"test021","女",25,"ttttdatttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(7,"test041","男",25,"ttdadatttttttt",newDate(),"htpp://wwww.baidu.com")); params.put("list",list); excelService.getExcel("t1.xlsx",params,newFile("D:\\test05.xlsx")); } }
导出成功
在线导出文件
@RestController publicclassTestController{ @Autowired ExcelServiceexcelService; @RequestMapping("test") publicvoidtestFile(HttpServletResponseresponse){ Mapparams=newHashMap(); List list=newArrayList<>(); list.add(newUserModel(1,"test01","男",25,"tttttttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(2,"test02","男",20,"tttttttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(3,"test04","女",25,"ttttddddasdadatttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(4,"test08","男",20,"ttttttdasdatttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(5,"test021","女",25,"ttttdatttttt",newDate(),"htpp://wwww.baidu.com")); list.add(newUserModel(7,"test041","男",25,"ttdadatttttttt",newDate(),"htpp://wwww.baidu.com")); params.put("list",list); excelService.getExcel("t1.xlsx",System.currentTimeMillis()+".xlsx",params,response); } }
源码地址
https://github.com/DavidLei08/BlogJxls.git
到此这篇关于SpringBoot快速集成jxls-poi(自定义模板,支持本地文件导出,在线文件导出)的文章就介绍到这了,更多相关SpringBoot集成jxls-poi内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。