1.用wps打开word文件, 另存为word Xml格式
2.修改xml文件后缀为ftl
3.将ftl模板放到资源目录下, 程序中读取模板,组装数据到map中
public class WordUtil {
private final Configuration configuration;
public WordUtil() {
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding("UTF-8");
}
/**
* 以下载的方式生成word,自定义路径
*
* @param dataMap
*/
public void createWord(String templateName,Map<String, Object> dataMap, String fileName, HttpServletResponse response) {
// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
// ftl文件存放路径
configuration.setClassForTemplateLoading(this.getClass(), "/template/ftl");
Template t;
try {
// 2.ftl为要装载的模板
t = configuration.getTemplate(templateName);
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) path = new File("");
System.out.println("path:" + path.getAbsolutePath());
//如果上传目录为/static/images/upload/,则可以如下获取:
File upload = new File(path.getAbsolutePath(), "static/upload/" + System.currentTimeMillis() + "/");
File download = new File(path.getAbsolutePath(), "static/download/" + System.currentTimeMillis() + "/");
if (!upload.exists()) upload.mkdirs();
if (!download.exists()) download.mkdirs();
File file=new File(upload+"/"+fileName);
FileWriter fileWriter=new FileWriter(file);
t.process(dataMap, fileWriter);
fileWriter.close();
// 由于ftl模板生成的文件实质上还是xml文件 , 所以有需要的还要转换一下格式
Document doc = new Document();
doc.loadFromFile(upload+"/"+fileName);
doc.saveToFile(download+"/"+fileName, FileFormat.Doc);
FileUtils.downloadFile(response,fileName,download.getAbsolutePath());
FileUtils.delFiles(upload);
FileUtils.delFiles(download);
} catch (TemplateException | IOException e) {
e.printStackTrace();
}
}
}
4.ftl模板中的数据替换处理
ftl模板中取值使用el表达式${} , 取值之前保险起见先判空 , <![CDATA[ ${noteTaker} ]]>可以保留样式
<#if noteTaker??> #判断不为空
<w:t><![CDATA[ ${noteTaker} ]]></w:t>
</#if>
循环集合