springboot+JXLS+Jexl实现报表模版生成报表

这篇具有很好参考价值的文章主要介绍了springboot+JXLS+Jexl实现报表模版生成报表。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

做这个项目的思路是由于公司基于自身发展,需要将之前的老项目平台拆解出来,由于之前的项目是所有的功能全部集中在一起,学习成本以及后续的扩展性来说,非常的不友好,并且由于之前设计人员的流失导致了项目无法进一步优化,所以想将其进行拆解,将单个功能模块进行拆分,形成微服务化,使每个功能的业务更加单一,也更加简单

经过使用了一段时间的老平台,发现目前公司的平台的一些设计确实非常的好,其中,报表的设计理念比市面上大多的报表工具设计都要好,为什么呢,因为我们公司是基于B to B的项目模式,所以,客户可能会经常临时性的提出一些报表需求,并且需要响应时间比较快速,所以我们需要一种基于模版即可生成报表的报表工具

报表工具的比对

基于模版形式的报表工具

目前市场上基于模版的是JXLS,他的优势是JXLS 是基于 Jakarta POI API 的 Excel 报表生成工具,可以生成精美的 Excel 格式报表。它采用标签的方式,类似 JSP 标签,写一个 Excel 模板,然后生成报表,非常灵活,简单!

缺点是它只可以导出03版本的excel

实现jxls

配置与使用
  1. 引入依赖

    				<dependency>
                <groupId>org.jxls</groupId>
                <artifactId>jxls</artifactId>
                <version>2.8.0</version>
            </dependency>
            <dependency>
                <groupId>org.jxls</groupId>
                <artifactId>jxls-poi</artifactId>
                <version>1.0.15</version>
            </dependency>
            <dependency>
                <groupId>net.sf.jxls</groupId>
                <artifactId>jxls-core</artifactId>
                <version>1.0.5</version>
            </dependency>
    
  2. 编写工具辅助类

    研发一个execl生成的工具类,其中加入了自定义方法,这个思想与lims平台设计中的Alog类类似,采用Jexl来进行实现,本项目采用的是jexl3

    package com.thyc.reportserver.utils;
    
    import com.thyc.reportserver.excelCal.CalTime;
    import org.apache.commons.jexl3.JexlBuilder;
    import org.apache.commons.jexl3.JexlEngine;
    import org.jxls.area.Area;
    import org.jxls.builder.AreaBuilder;
    import org.jxls.builder.xls.XlsCommentAreaBuilder;
    import org.jxls.common.CellRef;
    import org.jxls.common.Context;
    import org.jxls.expression.JexlExpressionEvaluator;
    import org.jxls.transform.Transformer;
    import org.jxls.util.TransformerFactory;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * @Description: excel辅助工具类
     * @Author: wanping
     * @Date: 6/13/23
     **/
    public class ExcelUtils {
        /***
         * excel导出到response
         * @param fileName   导出文件名
         * @param templateFile 模板文件地址
         * @param params     数据集合
         * @param response   response
         */
        public static void exportExcel(String fileName, InputStream templateFile, Map<String, Object> params,
                                       HttpServletResponse response) throws IOException {
            response.reset();
            response.setHeader("Accept-Ranges", "bytes");
            OutputStream os = 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 (IOException e) {
                throw e;
            }
        }
    
        /**
         * 导出excel到输出流中
         * @param templateFile 模板文件
         * @param params 传入参数
         * @param os 输出流
         * @throws IOException
         */
        public static void exportExcel(InputStream templateFile, Map<String, Object> params, OutputStream os) throws IOException {
            try {
                Context context = new Context();
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    //设置参数变量
                    context.putVar(key, params.get(key));
                }
                Map<String, Object> myFunction = new HashMap<>();
                myFunction.put("calTime", new CalTime());
                // 启动新的jxls-api 加载自定义方法
                Transformer trans = TransformerFactory.createTransformer(templateFile, os);
                JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) trans.getTransformationConfig().getExpressionEvaluator();
    //            evaluator.getJexlEngine().setFunctions(myFunction); 这个方法是2版本的
                JexlBuilder jb = new JexlBuilder();
                jb.namespaces(myFunction);
                JexlEngine je = jb.create();
                evaluator.setJexlEngine(je);
    
                // 载入模板、处理导出
                AreaBuilder areaBuilder = new XlsCommentAreaBuilder(trans);
                List<Area> areaList = areaBuilder.build();
                areaList.get(0).applyAt(new CellRef("sheet1!A1"), context);
                trans.write();
            } catch (IOException e) {
                throw e;
            } finally {
                try {
                    if (os != null) {
                        os.flush();
                        os.close();
                    }
                    if (templateFile != null) {
                        templateFile.close();
                    }
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }
    
    
  3. 编写计算类

    package com.thyc.reportserver.excelCal;
    
    import org.jxls.transform.poi.WritableCellValue;
    import org.jxls.transform.poi.WritableHyperlink;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @Description: excel计算时间方法
     * @Author: wanping
     * @Date: 6/13/23
     **/
    public class CalTime {
    
        /**
         * 格式化时间
         */
        public Object formatDate(Date date) {
            if (date != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                return dateStr;
            }
            return "--";
        }
    
        /**
         * 设置超链接方法
         */
        public WritableCellValue getLink(String address, String title) {
            return new WritableHyperlink(address, title);
        }
    
    }
    
  4. 编写剩下的测试用例

    service

    package com.thyc.reportserver.service;
    
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.File;
    import java.io.OutputStream;
    import java.util.Map;
    
    /**
     * @Description: TODO
     * @Author: wanping
     * @Date: 6/13/23
     **/
    public interface ExcelService {
    
        /**
         * 导出excel,写入文件中
         * @param templateFile
         * @param params
         * @param outputFile
         * @return
         */
        boolean getExcel(String templateFile, Map<String,Object> params, File outputFile);
    }
    
    

    impl

    package com.thyc.reportserver.service.impl;
    
    import com.thyc.reportserver.service.ExcelService;
    import com.thyc.reportserver.utils.ExcelUtils;
    import javax.servlet.http.HttpServletResponse;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.util.ResourceUtils;
    
    import java.io.*;
    import java.util.Map;
    
    /**
     * @Description: TODO
     * @Author: wanping
     * @Date: 6/13/23
     **/
    @Service
    public class ExcelServiceImpl implements ExcelService {
    
        private Logger logger = LoggerFactory.getLogger(getClass());
    
        /**
         * 模板文件的基础路径
         */
        @Value("${jxls.template.path}")
        private String templatePath;
    
        @Override
        public boolean getExcel(String templateFile, Map<String, Object> params, File outputFile) {
            FileInputStream inputStream = null;
            try {
                //获取模板文件的输入流
                inputStream = new FileInputStream(ResourceUtils.getFile(templatePath + templateFile));
                File dFile = outputFile.getParentFile();
                //文件夹不存在时创建文件夹
                if(dFile.isDirectory()){
                    if(!dFile.exists()){
                        dFile.mkdir();
                    }
                }
                //文件不存在时创建文件
                if(!outputFile.exists()){
                    outputFile.createNewFile();
                }
                //导出excel文件
                ExcelUtils.exportExcel(inputStream, params, new FileOutputStream(outputFile));
            } catch (IOException e) {
                logger.error("excel export has error" + e);
                return false;
            }
            return true;
        }
    }
    
    

    编写测试用例

    package com.thyc.reportserver;
    
    import com.thyc.reportserver.excelModel.UserModel;
    import com.thyc.reportserver.service.ExcelService;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import java.io.File;
    import java.util.*;
    
    @SpringBootTest
    class ReportServerApplicationTests {
    
        @Autowired
        ExcelService excelService;
    
        @Test
        void contextLoads() {
            Map<String, Object> params = new HashMap();
            List<UserModel> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                int i1 = i + 1;
                list.add(new UserModel(i1, "test" + i1, "男", 25 + i, "tttttttttt" + i1, new Date(), "htpp://wwww.baidu.com"));
            }
            params.put("list", list);
            excelService.getExcel("user1.xlsx", params, new File("/Users/wanping/IdeaProjects/ddd/report-server/excel/test01.xlsx"));
        }
    
    }
    
    1. 结果展示

    导入模版

springboot+JXLS+Jexl实现报表模版生成报表

结果

springboot+JXLS+Jexl实现报表模版生成报表

参考:https://www.jb51.net/article/195015.htm文章来源地址https://www.toymoban.com/news/detail-482355.html

到了这里,关于springboot+JXLS+Jexl实现报表模版生成报表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 转:Form 中调用并发请求生成报表并输出PDF的方法。

    Oracle Form中调用并发请求生成报表并输出为PDF的方法 (FND_CONCURRENT.WAIT_FOR_REQUEST)_rfb0204421的博客-CSDN博客 Form 中调用并发请求生成报表并输出PDF的方法。 要完成这个目的,首先要在ebs中注册报表,并注册模板。 然后再方法里先调用FND_REQUEST.ADD_LAYOUT添加模板,然后调用FND_REQ

    2024年02月09日
    浏览(31)
  • SpringBoot自动配置的模版引擎

    文章目录 目录 一、Thymeleaf 1.什么是Thymeleaf? 2.什么是模版引擎? 3.JAVA中的SPI(Service Provider interface)机制? 4.META-INF目录是干嘛用的? 总结         hymeleaf是试用于Web和独立环境的现代服务器端Java模版引擎 目的:它的主要目标是为您的开发工作流程带来优雅自然的模版-HTML可以再

    2024年02月08日
    浏览(14)
  • Apache POI,springboot中导出excel报表

    2.1 介绍 Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。 Apache POI 的应用场景: 银行网银系统导出交易明细 各种业务系统导出Excel报

    2024年02月02日
    浏览(26)
  • 使用SpringBoot+React搭建一个Excel报表平台

    摘要:本文由葡萄城技术团队于CSDN原创并首发。转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 Excel报表平台是一款功能强大、操作简单的系统平台,可以帮助用户上传、编辑和分析报表数据,实现数据可视化。 本文所

    2024年02月16日
    浏览(31)
  • VSCode 初次写vue项目并一键生成.vue模版

    1.安装vscode 官网地址:https://code.visualstudio.com/ 2.安装一个插件,识别vue文件 插件库中搜索Vetur,下图中的第一个,点击安装,安装完成之后点击重新加载 输入vue 按键盘的tab就行

    2024年02月01日
    浏览(30)
  • draggable + grid 拖拽插件 + 网格布局 动态生成首页模版

    背景:         1、首页模板由多个子组件组成,如图表、新闻、公告、轮播图等,一般都由前端引入子组件,写在固定的位置上,最终形成一个固定的首页模板;         2、像这样直接在代码中写死的首页没有灵活性,不同用户想展示出来的首页模板千篇一律;        

    2024年02月01日
    浏览(30)
  • vscode快速生成vue2及vue3模版

            在vue开发中,我们每次新建页面都会需要写一大部分重复代码。那么有什么办法,能够建立模版:vscode是可以进行相关配置的。       1.1 接着输入vue j 第二种打开方式

    2024年04月08日
    浏览(67)
  • jexl3动态计算表达式

    Java Expression Language (JEXL) 是一个表达式语言引擎,可以用来在应用或者框架中使用。JEXL 受Velocity 和 JSP 标签库 1.1 (JSTL) 的影响而产生的。需要注意的是, JEXL 并不是 JSTL 中的表达式语言的实现。 实时引擎里 动态逻辑计算分离 计算逻辑经常变化或者可视化逻辑配置 引入JAR包

    2024年02月11日
    浏览(34)
  • JAVA利用Freemarker模版动态生成并导出word文档(全网最详细)

    公司的某个需求,需要根据接口的信息生成一份word接口文档信息并支持导出功能。以前没做过这种需求,于是搜罗各种资料,最终发现java利用freemarker模版可以实现这个功能。 1、需要的环境 2、创建模板 1)展示word文档如下所示: 2)将word文档动态的参数替换成占位符,如下

    2024年02月16日
    浏览(34)
  • Meta 免费 AI 图像生成网站!保姆级教程+使用模版,附横向评测

    Meta 发布了一款新的免费 AI 图像生成器 你好,我是清风徐来 凛冬将至,AI 江湖,狼烟四起! 主战场是 LLM(大语言模型),OPEN AI 的 ChatGPT,全球公认第一,后面跟着 Claoud2,巴德十几个 官网 ChatGPT 如何开通,点这里 《保姆级教程!手把手教你用支付宝开通 ChatGPT plus!》 C

    2024年02月02日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包