这篇文章干什么?
使用代码将word模板内容进行替换,并输出替换后的word。
思路总览
1、准备一个word模板,将里面需要替换的值改为${变量名}
2、将word导出为xml,复制一份xml,将复制的这份xml文件改为.ftl结尾的文件。
3、引包,编写(复制)代码。
1、准备word模板
${test1}就是要通过代码替换的内容
2、转换文件格式
xml文件可以通过word导出,然后修改后缀为.ftl的文件,我们需要的就是.ftl文件。并将该文件放入到指定文件夹。
3、编写代码
引包:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
代码:
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
// 相关工具
@Autowired
private ExportFile exportFile;
// 常量
private Configuration configuration = null;
/**
* 输出word
*/
public void commonExportWord() {
// 获取map数据
Map<String,Object> map = getColumnMapById();
// 配置configuration
Template template = setConfiguration();
try{
// 输出文档路径及名称
Writer out = null;
String fileName = exportFile.encodingFilenameWord("filename");
// 文件的输出位置(输出到本地绝对路径里)
File outFile = new File("/Users/relycf/Desktop/test");
// 文件的输出位置(输出到项目相对路径里)
// File outFile = new File(exportFile.getAbsoluteFile(fileName));
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
template.process(map, out);
out.close();
// 如果你只是输出到本地,就可以不要下面这句,这句主要是为了返回流下载word。
// exportFile.fileDownload(fileName);
}catch (Exception e){
log.