根据模板动态生成word(一)使用freemarker生成word合集 - 根据模板生成word(3)

一、准备模板

1、创建模板文件

首先先建立一个word文件,输入模板内容freemaker的内容,下面是本次演示的word文件。

然后将word文件另存为 .xml 文件,然后再把文件后缀改成.ftl 。将项目的resource目录下建立一个templates目录(非必须步骤)将 模板文件放到templates目录下


打开模板文件按 Ctrl + Shift + L 将模板内容格式化。

2、处理模板

2.1 处理普通文本

处理文本比较简单,将需要替换文本中直接用占位符 ${} 替换即可。

这里发现一个问题因为之前在word格式时我就已经替换了变量,但是在ftl变量却被 拆分成多段了(见图1)。但是这样是freemaker是无法成功替换变量的,所以需要手动处理成到一个段里(如图2),关于这点实在太无语了,因为没有找到比较好的处理办法,只能手工处理,在实际的开发工作中曾经花了几个小时来做这件事情。
图1:

图2

2.2 处理表格

如果模板里需要用变量填充表格,建议模板里的表格像word文件一样建一个两行的表格。在模板中<<w:tbl>> 表示一个表格 、<w: tr> 表示一行、<w: tc> 表示一列。因为FreeMarker 是利用列表一行一行循环填充的,所以我们可以根据关键字找到<<w:tbl>>标签,因为第一个 <w: tr>是表头注意不要改到了,找到第二个<w: tr>在前后分别加上如下语句即可,后面的表格里后面的行<w: tr>需要删掉,建议模板里的表格像word文件一样建一个两行的表格即可这样就不用删了:

<#list itemList as item>
</#list>

替换后的模板如下:

2.3 处理图片

如果模板里需要用变量填充图片,建议先在word文件里插入一张图片,这样在模板文件里找到<pkg:binaryData>标签直接里面把里面的图片base64字符替换成变量即可,word里可以通过植入base64字符来展示图片:

替换前:

替换后:

<pkg:binaryData>${image1}</pkg:binaryData>

到此模板已经调整完成,接下来就可以开始写代码了。

二、项目代码

1、引入依赖

在项目的pom文件里引入如下依赖

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

2、生成代码

将图片转成Base64字符串的公共方法:

public static String getImageBase64Str(String imgFile) {
        try( InputStream in = new FileInputStream(imgFile)) {
            byte[] data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

根据模板文件生成word,主要生成的word的文件后缀必须是doc不能是docx,不然生成的文件无法打开。

public static void crateWord(Map<String, Object> dataMap, String templatePath, String targetFile){
        String path = templatePath.substring(0,templatePath.lastIndexOf("/"));
        String templateName = templatePath.substring(templatePath.lastIndexOf("/") + 1);
        try (FileOutputStream out = new FileOutputStream(targetFile);
             Writer writer = new BufferedWriter(new OutputStreamWriter(out, "utf-8"))){
            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(FreeMakerTest.class, path);
            //除了ClassForTemplateLoading外,另一种模板加载方式DirectoryForTemplateLoading,也可用
            //ClassPathResource resource = new ClassPathResource(path);
            //configuration.setDirectoryForTemplateLoading(resource.getFile());
            //加载模板
            Template template = configuration.getTemplate(templateName);
            //渲染模板
            template.process(dataMap, writer);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }

三、验证生成word

新建的列表数据实体类:

public class Arrears{
    private String name;
    private Integer num;

    private String endDay;

    public String getName() {
        return name;
    }

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

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getEndDay() {
        return endDay;
    }

    public void setEndDay(String endDay) {
        this.endDay = endDay;
    }
}

准备模板填充数据

private static Map<String, Object> prepareParam(){
        LocalDate currentDate = LocalDate.now();
        LocalDate endDate = currentDate.plusYears(1L);
        List<Arrears> arrearsList = new ArrayList<>();
        arrearsList.add(new Arrears(){{setName("一顿老魏");setNum(1);setEndDay("三月内");}});
        arrearsList.add(new Arrears(){{setName("贵州大黄牛");setNum(1);setEndDay("一年内");}});
        arrearsList.add(new Arrears(){{setName("v我50");setNum(1);setEndDay("一月内");}});

        //填充所需要的数据
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("debtor", "陈有楚");
        dataMap.put("nowYear", String.valueOf(currentDate.getYear()));
        dataMap.put("nowMonth", String.valueOf(currentDate.getMonthValue()));
        dataMap.put("nowDay", String.valueOf(currentDate.getDayOfMonth()));
        dataMap.put("arrears", "一顿老魏、贵州大黄牛、v我50");
        dataMap.put("endYear", String.valueOf(endDate.getYear()));
        dataMap.put("endMonth", String.valueOf(endDate.getMonthValue()));
        dataMap.put("endDay", String.valueOf(endDate.getDayOfMonth()));
        dataMap.put("arrearsList", arrearsList);
        dataMap.put("image1", getImageBase64Str("D:\\picture\\其他\\24-05-23-142418.png"));
        dataMap.put("creditor", "知北游");
        return dataMap;
    }

测试代码:

public static void main(String[] args) throws IOException {
        //准备参数
        Map<String, Object> dataMap = prepareParam();
        crateWord(dataMap,"/templates/qiantiao.ftl","D:\\test\\qiantiao.doc");
    }

测试结果:

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
FreeMarker 是一个Java模板引擎,它可以帮助我们根据模板生成各种文件,包括 Word 文档。下面是一个简单的示例,演示如何使用 FreeMarker 创建一个根据 FTL 模板生成 Word 文档的过程: 1. 创建一个 FreeMarker 的配置对象,并设置模板文件所在的目录: ``` Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDirectoryForTemplateLoading(new File("path/to/ftl/templates")); ``` 2. 从配置对象中获取模板对象: ``` Template template = cfg.getTemplate("template.ftl"); ``` 3. 准备数据模型,可以是一个 JavaBean、Map 或者其他类型的对象: ``` Map<String, Object> data = new HashMap<>(); data.put("title", "Hello, World!"); data.put("content", "This is a test document created by FreeMarker."); ``` 4. 创建一个 Writer 对象,用于输出生成Word 文档: ``` Writer out = new FileWriter(new File("path/to/output/doc.docx")); ``` 5. 将数据模型和 Writer 对象传递给模板对象,生成 Word 文档: ``` template.process(data, out); ``` 完整的示例代码如下: ``` import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class FreeMarkerDemo { public static void main(String[] args) throws Exception { // 创建 Configuration 对象 Configuration cfg = new Configuration(Configuration.VERSION_2_3_30); cfg.setDirectoryForTemplateLoading(new File("path/to/ftl/templates")); // 获取模板对象 Template template = cfg.getTemplate("template.ftl"); // 准备数据模型 Map<String, Object> data = new HashMap<>(); data.put("title", "Hello, World!"); data.put("content", "This is a test document created by FreeMarker."); // 创建输出流 Writer out = new FileWriter(new File("path/to/output/doc.docx")); // 生成 Word 文档 template.process(data, out); // 关闭输出流 out.close(); } } ``` 注意,上面的示例代码中使用模板文件是 FTL 格式,如果要生成 Word 文档,还需要将模板文件转换成 docx 或者其他 Word 文档格式。常见的工具包括 Apache POI 和 Docx4j 等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野生的狒狒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值