java使用freemarker导出word

来源:互联网 发布:john carmack 知乎 编辑:程序博客网 时间:2024/05/19 11:45

百度freemarker下载最新jar包。

步骤:

1、编写word模板test.docx,如下:


2、另存为xml文件test.xml。

3、插入循环操作的标签:


4、重命名为test.ftl(作为word的导出模板)。

5、编写生成word的代码,源码如下:

package word;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * @author LD */public class WordAction {public static void createWord() {/** 用于组装word页面需要的数据 */Map<String, Object> dataMap = new HashMap<String, Object>();/** 组装数据 */dataMap.put("remark", "这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容");List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();for (int i = 1; i <= 10; i++) {Map<String, Object> map = new HashMap<String, Object>();map.put("number", i);map.put("name", "name" + i);map.put("age", "age" + i);userList.add(map);}dataMap.put("userList", userList);/** 生成word */WordUtil.createWord(dataMap, "test1.ftl", "C:/Users/LD/Desktop/", "test_export.doc");System.out.println("生成成功!");}public static void main(String[] args) {createWord();}}
package word;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Map;import freemarker.template.Configuration;import freemarker.template.Template;/** * 生成word工具类 * @author LD * */public class WordUtil {/** * @param dataMap 数据 * @param templateName 模板名称 * @param filePath 导出文件路径 * @param fileName 导出文件名称 */@SuppressWarnings({ "deprecation" })public static void createWord(Map<String, Object> dataMap, String templateName, String filePath, String fileName) {try {// 创建配置实例Configuration configuration = new Configuration();// 设置编码configuration.setDefaultEncoding("UTF-8");// ftl模板文件统一放至 src/word 包下面configuration.setClassForTemplateLoading(WordUtil.class, "/word/");// 获取模板Template template = configuration.getTemplate(templateName);// 输出文件File outFile = new File(filePath + File.separator + fileName);// 如果输出目标文件夹不存在,则创建if (!outFile.getParentFile().exists()) {outFile.getParentFile().mkdirs();}// 将模板和数据模型合并生成文件Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));// 生成文件template.process(dataMap, out);// 关闭流out.flush();out.close();} catch (Exception e) {e.printStackTrace();}}}

6、右键运行WordAction,导出结果为:


7、注意事项:

word生成xml文件时,${user.name} 会被拆解开,中间夹杂一些标签,如下:


java运行的时候就会报错,如下:


原因:手动输入时,word误以为每个单词是一个对象,中间就会加载空格,导出就会有标签。

处理方法:

(1)生成xml之后,手动删除变量之间的标签

(2)编写word模板时,在其他编辑器中编号${user.name}这种变量,然后粘贴到word中

原创粉丝点击