导入jar
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
word转xml 通过浏览器来替换字段,然后保存为flt格式即可
javascript:document.body.contentEditable='true';document.designMode='on'; void 0
这里注意ftl中的语法 可以参考 https://hran.me/archives/freemarker.html/comment-page-3#menu_index_9
java 代码
@GetMapping(value = "/createUserListWord")
public ResponseEntity<Void> createUserListWord() {
fileService.createUserListWord();
return ResponseEntity.ok().build();
}
@Override
public void createUserListWord() {
Map<?, ?> root = initData(); //数据源对象
String template = "/templates/list1.ftl"; //模板文件的地址
String path = "E:\\list1.doc"; //生成的word文档的输出地址
WordUtil.process(root, template, path);
}
private Map<?, ?> initData() {
Map<String, Object> root = new HashMap<String, Object>();
List<User> users = new ArrayList<User>();
List<String> list = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("11", "林陈策");
map.put("22", "林陈策");
list.add("□");
list.add("□");
list.add("√");
list.add("□");
User zhangsan = new User("张三", "12", list, map);
User lisi = new User("李四", "12", list, map);
users.add(zhangsan);
users.add(lisi);
root.put("users", users);
root.put("title", "用户列表");
return root;
}
/**
* Created by lcc on 2017/9/13.
*/
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.Map;
public final class WordUtil {
private static Configuration configuration = null;
private WordUtil() {
throw new AssertionError();
}
/**
* 根据模板生成相应的文件
*
* @param root 保存数据的map
* @param template 模板文件的地址
* @param path 生成的word文档输出地址
* @return
*/
public static synchronized File process(Map<?, ?> root, String template, String path) {
if (null == root) {
throw new RuntimeException("数据不能为空");
}
if (null == template) {
throw new RuntimeException("模板文件不能为空");
}
if (null == path) {
throw new RuntimeException("输出路径不能为空");
}
File file = new File(path);
String templatePath = template.substring(0, template.lastIndexOf("/"));
String templateName = template.substring(template.lastIndexOf("/") + 1, template.length());
if (null == configuration) {
configuration = new Configuration(Configuration.VERSION_2_3_23); // 这里Configurantion对象不能有两个,否则多线程访问会报错
configuration.setDefaultEncoding("utf-8");
configuration.setClassicCompatible(true);
}
configuration.setClassForTemplateLoading(WordUtil.class, templatePath);
Template t = null;
try {
t = configuration.getTemplate(templateName);
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
t.process(root, w); // 这里w是一个输出地址,可以输出到任何位置,如控制台,网页等
w.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return file;
}
}