1.创建一个word模板文件,填入需要生成的信息,需要动态传入的数据用${变量名}替换,如图。
2.将文件另存为xml格式。
3. 打开保存的xml文档,格式化xml文档,并检查${变量名} 是否分开,如果分开请手动修正。
4.将xml格式改为ftl格式。
5.编写代码
1)新建一个maven工程,导入依赖。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2)新建一个WordUtil工具类
省去import
public class WordUtil {
/**
* 使用FreeMarker自动生成Word文档
* @param dataMap 生成Word文档所需要的数据
* @param fileName 生成Word文档的全路径名称
* @param templateName 模板文件
* @param templatePath 模板路径
* @throws Exception
*/
public static void generateWord(Map<String, Object> dataMap, String fileName,String templateName,String templatePath) throws Exception {
// 设置FreeMarker的版本和编码格式
//Configuration configuration = new Configuration(new Version("2.3.28"));
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
// 设置FreeMarker生成Word文档所需要的模板的路径
configuration.setDirectoryForTemplateLoading(new File(templatePath));
// 设置FreeMarker生成Word文档所需要的模板
Template t = configuration.getTemplate(templateName, "UTF-8");
// 创建一个Word文档的输出流
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "UTF-8"));
//FreeMarker使用Word模板和数据生成Word文档
t.process(dataMap, out);
out.flush();
out.close();
}
}
3)编写测试类
@Test
public void test02() throws IOException {
String path="D:\\IDEA_code\\javaUtils\\src\\main\\resources\\";
String fileName="D:\\logs\\测试.doc";
String templateName="测试1.ftl";
String templatePath="D:\\IDEA_code\\javaUtils\\src\\main\\resources\\";
Map<String,Object> map=new HashMap<>();
map.put("name","sdsd");
map.put("age",12);
map.put("city","北京");
try {
WordUtil.generateWord(map,fileName,templateName,templatePath);
} catch (Exception e) {
e.printStackTrace();
System.out.println("出现异常");
}
System.out.println("生成成功");
}
5.最后生成文档