项目实站—填充Word模版并生成Word文档

用途:生成电子履历或者固定格式文档

模版制作

1、新建一个word文档,填入固定内容;

在这里插入图片描述

2、在要用程序写入数据的地方,插入-文档部件-域-自动图文集列(微软Word叫AUTOTEXTLIST),标签名和程序标签要对应;
在这里插入图片描述
在这里插入图片描述
3、文档保存为Word XML格式;
在这里插入图片描述

然后将word xml文件拷贝到项目的resources/templates目录下

添加依赖

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

工具类

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;

/**
 * @program: world
 * @description: doc工具类
 * @author: XinHai.Ma
 * @create: 2021-09-09 15:54
 */
public class DocUtils {

    public static void saveWord(String filePath, Map<String,Object> 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);
        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<String, Object> 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 {
                writer.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
		转换成字节数组
		templateName = /templates/xxxx.xml
	*/
	public static byte[] genDocBytes(Map<String, Object> dataMap,String templateName){
        // 加载FreeMarker模板
        Configuration config = new Configuration(Configuration.VERSION_2_3_26);
        config.setClassForTemplateLoading(DocUtils.class, "/");
        Template template = null;
        byte[] wordBytes = null;
        try {
            template = config.getTemplate(templateName);
            // 生成Word文档输出流
            ByteArrayOutputStream osWord = new ByteArrayOutputStream();
            Writer writer = new OutputStreamWriter(osWord, StandardCharsets.UTF_8);
            template.process(dataMap, writer);
            writer.close();
            // 获取word输出流
            wordBytes = osWord.toByteArray();
            osWord.close();
        }catch (Exception e){

        }
        return wordBytes;
    }

}

测试

import com.maxinhai.world.utils.DocUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

/**
 * @program: world
 * @description: doc测试用例
 * @author: XinHai.Ma
 * @create: 2021-09-09 16:16
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class DocTests {

    @Test
    public void test() {
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", "献祭之主");
            dataMap.put("author", "王信");
            dataMap.put("createDate", "2021年9月9日");
            dataMap.put("title_item1", "第14章 :我父母为了保护北马城所牺牲!");
            dataMap.put("content", "我父母为了保护北马市,死在了魔兽攻城中!");
            DocUtils.saveWord("C:\\Users\\86186\\Documents\\献祭之主.docx", dataMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

效果

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值