SpringBoot动态导出word文档(完美实整教程 复制即可使用,不能实现你找我)

这篇具有很好参考价值的文章主要介绍了SpringBoot动态导出word文档(完美实整教程 复制即可使用,不能实现你找我)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

背景

最近有一个需求是需要动态导出合同、订单等信息,导出一个word文档供客户进行下载查看。

需要导出的word文件,主要可以分为两种类型。

  1. 导出固定内容和图片的word文档
  2. 导出表格内容不固定的word文档

经过对比工具,我实践过两种实现方式。第一种是FreeMarker模板来进行填充;第二种就是文中介绍的POI-TL。

这里我推荐使用POI-TL

介绍

POI-TL是word模板引擎,基于Apache POI,提供更友好的API。

目前最新的版本是1.12.X,POI对应版本是5.2.2。

这里需要注意的是POI和POI-TL有一个对应的关系。

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

准备工作

我使用的POI-TL版本是1.10.0

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

<dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.7</version>
        </dependency>

快速开始

流程:制作模板->提供数据->渲染模板->下载word

注意:需要填充的数据需要使用{{}}来表示。

1. 导出固定内容和图片的word文档

准备模板

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

模板保存为docx格式,存放在resource目录下

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

提供数据

private Map<String, Object> assertMap() {
        Map<String, Object> params = new HashMap<>();
        params.put("name", "努力的蚂蚁");
        params.put("age", "18");
        params.put("image", Pictures.ofUrl("http://deepoove.com/images/icecream.png").size(100, 100).create());
        return params;
    }

工具方法

/**
     * 将项目中的模板文件拷贝到根目录下
     * @return
     */
    private String copyTempFile(String templeFilePath) {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(templeFilePath);
        String tempFileName = System.getProperty("user.home") + "/" + "1.docx";
        File tempFile = new File(tempFileName);
        try {
            FileUtils.copyInputStreamToFile(inputStream, tempFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return tempFile.getPath();
    }
private void down(HttpServletResponse response, String filePath, String realFileName) {
        String percentEncodedFileName = null;
        try {
            percentEncodedFileName = percentEncode(realFileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=").append(percentEncodedFileName).append(";").append("filename*=").append("utf-8''").append(percentEncodedFileName);

        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
             // 输出流
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
     * 百分号编码工具方法
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

编写接口

@RequestMapping("genera")
    public void genera(HttpServletResponse response) {
        //1.组装数据
        Map<String, Object> params = assertMap();
        //2.获取根目录,创建模板文件
        String path = copyTempFile("word/1.docx");
        String fileName = System.currentTimeMillis() + ".docx";
        String tmpPath = "D:\\" + fileName;
        try {
            //3.将模板文件写入到根目录
            //4.编译模板,渲染数据
            XWPFTemplate template = XWPFTemplate.compile(path).render(params);
            //5.写入到指定目录位置
            FileOutputStream fos = new FileOutputStream(tmpPath);
            template.write(fos);
            fos.flush();
            fos.close();
            template.close();
            //6.提供前端下载
            down(response, tmpPath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7.删除临时文件
            File file = new File(tmpPath);
            file.delete();
            File copyFile = new File(path);
            copyFile.delete();
        }
    }

对于图片的格式,POI-TL也提供了几种方式来提供支撑。

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

测试

请求接口:http://127.0.0.1:1000/file/genera

效果如下:

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

2. 导出表格内容不固定的word文档

表格动态内容填充,POI-TL提供了3种方式。

  1. 表格行循环
  2. 表格列循环
  3. 动态表格。

第二种和第三种都可以实现表格填充,但我个人感觉第一种更方便一点,这里我只介绍【表格行循环】实现方式。

LoopRowTableRenderPolicy 是一个特定场景的插件,根据集合数据循环表格行。

注意:

  1. 模板中有两个list,这两个list需要置于循环行的上一行。
  2. 循环行设置要循环的标签和内容,注意此时的标签应该使用[]

准备模板

springboot导出word,java,java,poi-tl,word动态导出,SpringBoot

提供数据

学生实体类

public class Student {
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

学生word类

public class StudentTable {
    private String title;
    private List<Student> studentList;

    private List<Student> studentList1;

    public List<Student> getStudentList1() {
        return studentList1;
    }

    public void setStudentList1(List<Student> studentList1) {
        this.studentList1 = studentList1;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

表格数据

private StudentTable assertData() {
        StudentTable table = new StudentTable();
        table.setTitle("我是标题");
        List<Student> studentList = new ArrayList<>();
        Student student = new Student();
        student.setName("张三");
        student.setAge("18");
        studentList.add(student);
        Student student1 = new Student();
        student1.setName("李四");
        student1.setAge("20");
        studentList.add(student1);
        Student student2 = new Student();
        student2.setName("王五");
        student2.setAge("21");
        studentList.add(student2);
        Student student3 = new Student();
        student3.setName("马六");
        student3.setAge("19");
        studentList.add(student3);
        table.setStudentList(studentList);
        table.setStudentList1(studentList);
        return table;
    }

编写接口

@RequestMapping("dynamicTable")
    public void dynamicTable(HttpServletResponse response) {
        //1.组装数据
        StudentTable table = assertData();
        //2.获取根目录,创建模板文件
        String path = copyTempFile("word/2.docx");
        //3.获取临时文件
        String fileName = System.currentTimeMillis() + ".docx";
        String tmpPath = "D:\\" + fileName;
        try {
            //4.编译模板,渲染数据
            LoopRowTableRenderPolicy hackLoopTableRenderPolicy = new LoopRowTableRenderPolicy();
            Configure config =
                    Configure.builder().bind("studentList", hackLoopTableRenderPolicy).bind("studentList1", hackLoopTableRenderPolicy).build();
            XWPFTemplate template = XWPFTemplate.compile(path, config).render(table);
            //5.写入到指定目录位置
            FileOutputStream fos = new FileOutputStream(tmpPath);
            template.write(fos);
            fos.flush();
            fos.close();
            template.close();
            //6.提供下载
            down(response, tmpPath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7.删除临时文件
            File file = new File(tmpPath);
            file.delete();
            File copyFile = new File(path);
            copyFile.delete();
        }
    }

测试

请求接口:http://127.0.0.1:1000/file/dynamicTable

效果如下:
springboot导出word,java,java,poi-tl,word动态导出,SpringBoot文章来源地址https://www.toymoban.com/news/detail-780343.html

到了这里,关于SpringBoot动态导出word文档(完美实整教程 复制即可使用,不能实现你找我)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • java利用模板导出word文档

    1.依赖: 1.普通数据 2.表格 3.1编辑模板:选中区域,按ctrl+F9,右键编辑域,选择邮件合并,输入参数 参数后面加“!”可以避免参数为null而报错,  3.2.代码:  3.3展示 1.数据类型 布尔型:等价于java的Boolean类型,不同的是不能直接输出,可转化为字符串输出 日期型:等价于

    2024年02月04日
    浏览(36)
  • 【飞书】飞书导出md文档 | 飞书markdown文档导出 | 解决飞书只能导出pdf word

    github地址:https://github.com/Wsine/feishu2md 这是一个下载飞书文档为 Markdown 文件的工具,使用 Go 语言实现。 请看这里:招募有需求和有兴趣的开发者,共同探讨开发维护,有兴趣请联系。 《一日一技 | 我开发的这款小工具,轻松助你将飞书文档转为 Markdown》 配置文件需要填写

    2024年02月15日
    浏览(38)
  • 【PHPWrod】使用PHPWord导出word文档

    目的:PHP通过PHPWord类库导出文件为word。 开发语言及类库:ThinkPHP、PHPWord 项目根目录使用composer安装PHPWord,安装完成后会在vendor目录下生成phpoffice文件夹,就是PHPWord类库 前端代码 PHP代码 1、前端:先使用按钮事件,在点击事件里去请求后端返回的word文件的地址(这个地址是

    2024年02月09日
    浏览(26)
  • Java文件:XWPFDocument导出Word文档

    在Java项目开发过程中经常会遇到导出Word文档的业务场景。XWPFDocument是apache基金会提供的用户导出Word文档的工具类。 XWPFDocument:代表一个docx文档 XWPFParagraph:代表文档、表格、标题等各种的段落,由多个XWPFRun组成 XWPFRun:代表具有同样风格的一段文本 XWPFTable:代表一个表格

    2024年01月18日
    浏览(26)
  • Java 实现导出 Word 文档的方法详解

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 在 Java 应用程序中,有时候我们需要将数据导出为 Word 文档,以便进行文档的编辑、打印或共享。本文将介绍如何

    2024年02月15日
    浏览(29)
  • vue中实现将html导出为word文档

    需求:将页面整成理想样式,将想要的那一部分页面导出成word,不用写模板,按照当前页面样式导出即可。(简易版) 保姆级别教程: 第一步:安装需要的依赖 第二步:给导出那部分的容器起个id名 第三步:在需要的地方引入依赖 第四步:获取dom节点myContainer并导出(我写

    2024年02月11日
    浏览(29)
  • vue简易导出word文档——docxtemplater使用介绍

    好久不见,上班时间 时间紧急,把领导要写的文档写好复制了一份发给大家(斜眼笑)。 一、下载依赖 ​​二、在 public 文件夹下创建docx模板 如果后面步骤报错找不到模板,打开docx文档 另存为覆盖 当前文件即可。 三、新建js文件,加入导出实现代码 四、调用页面引入方

    2024年02月14日
    浏览(29)
  • postman 文档、导出json脚本 导出响应数据 response ,showdoc导入postman json脚本 导出为文档word或markdown

    保存、补全尽可能多的数据、描述 保存响应数据 Response :(如果导出接口数据,会同步导出响应数据) 请求接口后,点击下方 Save as Example  可以保存响应数据到本地(会在左侧接口下新增一个e.g. 文件用来保存响应数据) 完善文档相关信息 :接口名、参数描述、自定义文

    2024年02月11日
    浏览(32)
  • Android 基于POI库,根据模板导出word文档

    由于项目需求,需要根据用户提供的word模板,填充动态内容生成新的word,为了记录自己的踩坑日记,记录一下。 Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对文档读和写的功能。 这里给出官网链接-POI官网,同时下载版本也在官网链接中,可

    2024年01月18日
    浏览(37)
  • 动态导出word

    参数如下: 效果图如下: 本demo仅用于学习使用,可根据具体业务对代码进行适当整改使用。 不足之处,请留言以便完善整改。

    2024年02月10日
    浏览(18)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包