1. 准备模板文件,将所需要生成的信息使用 ${} 占位符,也可以动态生成图片,不过需要提前将图片放入所需位置。并将word 文档另存为 xml 文件
注意:这里必须存为 word 2003 xml 格式,否则会有问题
2. 将xml 文件更改后缀为 ftl,并放入resources目录下自定义一个文件夹下,我这里定义名称为templates。
3.idea中打开ftl 文件,会是下面这种样子,图片会议base64编码的格式存在
删除图片base64编码,使用快捷键 ctrl+alt+l 格式化文件。在ftl文件中做部分修改。
如:用户列表是list集合遍历的形式动态展示,所以需要遍历列表标签并展示数据。遍历的语法如下:<#list 集合 as 对象名> </#list>。别忘记关闭list。并放在 w:tr 标签前(换行符)。
并将list集合属性修改为 对象名.属性名称,如 user.name
序号可用 user_index+1
4.修改图片属性,当我们删出base64 编码后,会是下面这个样子,将原base64编码替换为${} 占位符
注:若在集合中循环插入图片,得修改name和src字段名称,不能重复。可使用 ${user_index}
5. 引入freemarker的pom依赖和工具类
pom 依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
工具类
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import java.io.*;
import java.util.Map;
public class WordExportUtil {
private Configuration cfg;
public WordExportUtil() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(WordExportUtil.class, "/templates");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
}
public void createWordDocument(Map<String,Object> data, String outputFilePath,String templateName) throws Exception {
Template template = cfg.getTemplate(templateName);
Writer out = new BufferedWriter(new FileWriter(outputFilePath));
template.process(data, out);
out.close();
}
}
注:cfg.setClassForTemplateLoading(WordExportUtil.class, "/templates"); 此处"/templates" 需和你在resources下新建文件夹名称保持一致
6.测试类
测试代码
@Test
public void exportWord() throws Exception {
String templateName = "测试01.ftl"; //你的ftl文件名称
String outputFilePath = "G:\\test.doc"; //输出文件路径
Map<String, Object> data = new HashMap<>();
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User user = new User();
user.setName("张三"+i);
user.setAge(18 + i);
user.setPhone("1234567890"+i);
user.setRemark("备注" + i);
users.add(user);
}
data.put("users", users);
data.put("title","测试标题");
data.put("number","54321");
//图片转为base64
String imagePath ="G:\\猫咪2.jpg";
// 读取图片文件的字节内容
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
// 使用Base64进行编码
String encodedImage = Base64.getEncoder().encodeToString(imageBytes);
data.put("image",encodedImage);
new WordExportUtil().createWordDocument(data, outputFilePath, templateName);
}