1:需要的jar
freemarker.jar https://pan.baidu.com/s/105Ma9aVPha8YvlBkuuO4bA 提取码:b9k8
或者
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2:Java 代码
******************************开始****************************************
package word.moban1;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* 通过模板下载word word 转成 ftl
* @author cheng
* freemarker.jar
* <dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.32</version>
</dependency>
*
*/
public class mobandachuWord {
public static String exportWord(Map<String,Object> dataMap, String templName, String fileName) throws ParseException {
String pathName = fileName;
String appPath = mobandachuWord.class.getResource("").toString() +templName+ ".ftl";
appPath = appPath.replace("file:/", "");
//path = path.replace("/", "//");
appPath = appPath.substring(0, appPath.lastIndexOf("/"))+"/";
System.out.println("路径:"+appPath);
try {
SimpleDateFormat sdfNow = new SimpleDateFormat("yyyy-MM-dd");
String nowDateStr = sdfNow.format(new Date().getTime());
Date nowDate = sdfNow.parse(nowDateStr);
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(appPath));
Template template = configuration.getTemplate(templName + ".ftl", "utf-8");
SimpleDateFormat sdfNow1 = new SimpleDateFormat("yyyyMMddHHmmss");
pathName = fileName +sdfNow1.format(new Date())+".doc";
String download_path = appPath;
// 输出文档路径及名称
if (!(new File(download_path).isDirectory())) {
new File(download_path).mkdirs();
}
File outFile = new File(download_path + pathName);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 102400);
template.process(dataMap, out);
} catch (Exception e) {
e.printStackTrace();
}
return pathName;
}
public static void main(String[] args) throws Exception {
Map<String,Object> dataMap =new HashMap();
dataMap.put("name", "测试数据导出");
dataMap.put("title1", "测试数标题");
dataMap.put("text1", "测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出测试数据导出");
//构造数据 , 模板名称 , 导出word名称
exportWord(dataMap,"123","测试模板导出");
System.out.println("导出成功!!!!!!!!路径:");
}
}
******************************结束****************************************
3:模板设置
1:创建word,word的样式直接自己编辑
2:将word 内容更改为 占位符 ${ } {}内写变量 ,word的样式不变
另存为 xml文件
https://tool.ip138.com/xml/
将ftl文件 和 Java 类 放在同一个文件夹下 执行Java main方法 ,生成文件的路径 打印再控制台了
标签:word,freemarker,导出,测试数据,import,new,ftl From: https://www.cnblogs.com/xueershewang/p/17207847.html