- 新建maven项目
2.导入pom文件 ,这里是我的pom文件,里面有freemaker的包
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>get</groupId>
<artifactId>jar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>jar</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</dependency>
<!-- poi操作 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version>
</dependency>
</dependencies>
</project>
3.准备好模板文件
- 在当前项目目录下新建模板文件文件夹(用来放模板文件)
- 在该文件夹内新建test.docx文件,并且另存为test.xml
- 编辑test.xml文件,标记要替换的地方
- 将xml文件改成ftl文件
插入代码,并且运行
package com.freemaker_test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException, TemplateException
{
final Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
File file = new File("");
String templateFilePath = file.getCanonicalPath() + "\\template_file";//模板文件路径
String outFilePath = templateFilePath + "\\out\\out.doc";//输出doc文件路径
cfg.setDirectoryForTemplateLoading(new File(templateFilePath));//从模板文件目录获取模板文件
cfg.setDefaultEncoding("UTF-8");//一定要设置编码,如果编码不统一会导致乱码问题
Template template = cfg.getTemplate("test.ftl", "UTF-8");
Map<String, String> root = new HashMap<String, String>();
root.put("TestData", "test_data");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "UTF-8"));
template.process(root, out);
}
}