关于使用freemarker导出word
java使用FreeMarker导出word
一、 先做一个word模板
二、 将该word文件另存为xml格式(注意是另存为,不是直接改扩展名)
三、 打开xml文件把要导出的文字都加上${xxx} 例如:${bianhao}
导出表格要在目标行(例如:bianhao这一行)的<w:tr></w:tr>标签包一个<#list xxx as xxx></#list> 例如:<#list userlist as userlist >标签,把要导出的文字都加上${ userlist . xxx} 例如:${ userlist . bianhao },保存后把xml文件后缀名改成 .ftl
四、 将文件保存到指定的文件夹下,在pom文件中导入FreeMarker.jar
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
五、 Java代码如下(这里是一个测试方法)
import freemarker.template.Configuration; import freemarker.template.TemplateException; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class WordTest { private Configuration configuration = null; public WordTest(){ configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); } public static void main(String[] args) { WordTest test = new WordTest(); test.createWord(); } public void createWord(){ Map<String,Object> dataMap=new HashMap<String,Object>(); getData(dataMap); //模板文件所在路径 // configuration.setClassForTemplateLoading(this.getClass(), ""); try { configuration.setDirectoryForTemplateLoading(new File("D:\\IdeaProjects\\SpringMVC\\src\\word")); } catch (IOException e) { e.printStackTrace(); } freemarker.template.Template t=null; try { //获取模板文件 t = configuration.getTemplate("test.ftl"); } catch (IOException e) { e.printStackTrace(); } //导出文件 File outFile = new File("D:/outFile"+Math.random()*10000+".doc"); Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile))); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { //将填充数据填入模板文件并输出到目标文件 t.process(dataMap, out); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void getData(Map<String, Object> dataMap) { dataMap.put("a", "/"); dataMap.put("b", "名称"); dataMap.put("c", "性别"); dataMap.put("d", "电话"); dataMap.put("e", "邮箱"); dataMap.put("f", "职位"); dataMap.put("A", "/"); dataMap.put("B", "名称"); dataMap.put("C", "经理"); dataMap.put("D", "电话"); dataMap.put("E", "邮箱"); List<Map<String,Object>> userlist = new ArrayList<Map<String,Object>>(); for (int i = 0; i < 50; i++) { Map<String,Object> map = new HashMap<String,Object>(); map.put("bianhao", i); map.put("name", "刘慧文"+i); map.put("sex", "男"+i); map.put("phone", "15122693135"+i); map.put("email", "1305156911@qq.com"+i); map.put("zhiwei", "开发工程师"+i); userlist.add(map); } List<Map<String,Object>> deptlist = new ArrayList<Map<String,Object>>(); for (int i = 0; i < 50; i++) { Map<String,Object> map = new HashMap<String,Object>(); map.put("BIANHAO", i); map.put("NAME", "刘慧文"+i); map.put("JINGLI", "张经理"+i); map.put("PHONE", "15122693135"+i); map.put("EMAIL", "1305156911@qq.com"+i); deptlist.add(map); } dataMap.put("userlist", userlist); dataMap.put("deptlist", deptlist); } }
六、 导出效果