栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java springboot 写入word文档(word模版)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java springboot 写入word文档(word模版)

文章目录
  • 一共找了两个方案,建议使用第一个,制作模版比较方便。
  • 方案一 poi-tl
    • 1.1 依赖
    • 1.2 使用
      • 1.2.1 工具类 (先要有模版)
      • 1.2.2 使用
    • 1.3 word模版的创建
  • 方案二 word-freemaker
      • 注意:
    • 2.1 依赖
    • 2.2 使用
      • 2.2.1 工具类(先要有模版才行)
      • 2.2.2 使用
    • 2.3. word的模板创建
      • 2.3.1 这是一个模版。。。

一共找了两个方案,建议使用第一个,制作模版比较方便。 方案一 poi-tl

可以用office,也可用用wps

1.1 依赖
        
        
            com.deepoove
            poi-tl
            1.6.0
        
1.2 使用 1.2.1 工具类 (先要有模版)
package com.mods.study.lessons;

import com.deepoove.poi.XWPFTemplate;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class DocUtils {
	//map里传的是数据
    public static void generateWord(Map map) throws IOException {
        String mobanPath  = "D:\Users\Administrator\Desktop\add.docx"
        
        String outPath = "c:\word-doc2\" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSS") + "-" + "一个word文档.docx";//文件输出地址,指定到文件

        //.文件地址的目录  是否存在,不存在新建目录
        File dest = new File(outPath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        XWPFTemplate render = XWPFTemplate.compile(mobanPath).render(map);
        //这个路径指定的是
        render.writeToFile(outPath);
    }
}

1.2.2 使用
package com.mods.study.controller;

import com.mods.common.result.Result;
import com.mods.study.lessons.DocUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/word-doc")
@Api(tags = "WriteWordController", description = "生成word文件")
public class WriteWordController {
    @GetMapping
    public Result write() {
        try {
            Map dataMap = new HashMap<>();
            dataMap.put("title", "这是一个标题");
            dataMap.put("author", "这是一个作者名称");
            DocUtils.generateWord(dataMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result();
    }
}

1.3 word模版的创建

新建一个word,正常写内容。需要java替换的地方, 用两层花括号包起来就好了。

然后把模版的路径放到工具类里,输出路径也放到方法里即可。

标题 : {{title}}

作者 : {{author}}
方案二 word-freemaker 注意:

要用wps进行创建模版,要用wps打开生成后的word。。。用office会报错,正在查找原因和优化中。。。

2.1 依赖


    org.freemarker
    freemarker
    2.3.30




   org.springframework.boot
   spring-boot-starter-freemarker

2.2 使用 2.2.1 工具类(先要有模版才行)
package com.mods.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;


public class DocUtils {

    public static void saveWord(String filePath, Map dataMap) throws IOException {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(DocUtils.class, "/");
        Template template = configuration.getTemplate("templates/template.xml");
        InputStreamSource streamSource = createWord(template, dataMap);
        if (streamSource != null) {
            InputStream inputStream = streamSource.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(filePath);
            byte[] bytes = new byte[1024];
            while ((inputStream.read(bytes)) != -1) {
                outputStream.write(bytes);// 写入数据
            }
            inputStream.close();
            outputStream.close();
        }
    }

    public static InputStreamSource createWord(Template template, Map dataMap) {
        StringWriter out = null;
        Writer writer = null;
        try {
            out = new StringWriter();
            writer = new BufferedWriter(out, 1024);
            template.process(dataMap, writer);
            return new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
2.2.2 使用
package com.mods.study.controller;

import com.mods.common.result.Result;
import com.mods.common.utils.DocUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/word-doc")
@Api(tags = "WriteWordController", description = "生成word文件")
public class WriteWordController {

    @GetMapping
    public Result write() {
        //.文件地址
        String filePath = "c:\word-doc\";
        String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSS") + "-" + "一个word文档.docx";
        //.文件地址是否存在,不存在新建目录
        File dest = new File(filePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        try {
            Map dataMap = new HashMap<>();
            dataMap.put("title", "这是一个标题");//这里的title对应模版里的域 ${title}
            dataMap.put("author", "这是一个作者名称");//这里的author对应模版里的域 ${author}
            DocUtils.saveWord(filePath + filename, dataMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result();
    }
}

2.3. word的模板创建

  • 新建一个word,

  • 在word中正常填写文字。

  • 填充。(域 :用于给java替换)

注意,在需要用java去填充的地方:

插入-> 文档部件 -> 域 - > 选择 :AutoTextList( 自动图文集列 ) -> 域属性 填:${keyword}

注意域属性的格式${属性名}。要和java代码中的一致。

  • 保存成xml格式。

文件->另存为 -> 格式选(xml文档 *.xml)

  • 放到程序中,(和工具类中的路径和名称一致)成为模版
2.3.1 这是一个模版。。。


Windows UserAdministrator42022-05-09T11:44:00Z2022-05-09T12:35:06Z158401621P R C1121142052-11.1.0.1169133AE7A1651F44C2FA8B3C2C65D765870标题 AUTOTEXTLIST    * MERGEFORMAT ${title}作者 AUTOTEXTLIST    * MERGEFORMAT ${author}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/872516.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号