`

使用freemarker生成word,步骤详解带源代码

阅读更多

1、   步骤

1、    用word编辑好模板

1、 普通字符串替换为 ${string}

2、 表格循环用标签

<#list  userList as user>

姓名:${user.userName}   , 性别:${user.sex}

</#list>

word模板原型如下图:

最终生成的结果如下:

2、    将word模板另存为xml格式

 

选中 [ 仅保存数据 ]

 

选择 [ 保持wordML(K) ]

3、    将xml模板文件后缀名改为.ftl

4、    编辑ftl文件

搜索关键字,补入 <#list userList  as user> </#list>或其它freemarker标签

如下图:

2、   Java代码

 

package com.lun.utils;


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;


/**
 * @Desc:word操作工具类
 * @Author:张轮
 * @Date:2014-1-22下午05:03:19
 */
public class WordUtil {
   
/**
* @Desc:生成word文件
* @Author:张轮
* @Date:2014-1-22下午05:33:42
* @param dataMap word中需要展示的动态数据,用map集合来保存
* @param templateName word模板名称,例如:test.ftl
* @param filePath 文件生成的目标路径,例如:D:/wordFile/
* @param fileName 生成的文件名称,例如:test.doc
*/
    @SuppressWarnings("unchecked")
public static void createWord(Map dataMap,String templateName,String filePath,String fileName){
        try {
        //创建配置实例 
        Configuration configuration = new Configuration();
        
        //设置编码
            configuration.setDefaultEncoding("UTF-8");
            
            //ftl模板文件统一放至 com.lun.template 包下面
            configuration.setClassForTemplateLoading(WordUtil.class,"/com/lun/template/");
            
            //获取模板 
            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();
        }
    }
}

 

 

package com.lun.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.struts2.ServletActionContext;
import com.lun.utils.WordUtil;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @Desc:生成word
 * @Author:张轮
 * @Date:2014-1-22下午04:52:03
 */
@SuppressWarnings("serial")
public class WordAction  extends ActionSupport{

 private String filePath; //文件路径
 private String fileName; //文件名称
 private String fileOnlyName; //文件唯一名称

 /**
  * @Desc:生成word文档
  * @Author:张轮
  * @Date:2014-1-22下午07:29:58
  * @return
  */
    public String createWord() {
        /** 用于组装word页面需要的数据 */
        Map<String, Object> dataMap = new HashMap<String, Object>();
        
        /** 组装数据 */
        dataMap.put("userName","张三");
        
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
        dataMap.put("currDate",sdf.format(new Date()));
        
        dataMap.put("content","这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容这是其它内容");
        
        List<Map<String, Object>> newsList=new ArrayList<Map<String,Object>>();
        for(int i=1;i<=10;i++){
         Map<String, Object> map=new HashMap<String, Object>();
         map.put("title", "标题"+i);
         map.put("content", "内容"+(i*2));
         map.put("author", "作者"+(i*3));
         newsList.add(map);
        }
        dataMap.put("newsList",newsList);
        
        /** 文件名称,唯一字符串 */
        Random r=new Random();
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        StringBuffer sb=new StringBuffer();
        sb.append(sdf1.format(new Date()));
        sb.append("_");
        sb.append(r.nextInt(100));
        
        //文件路径
        filePath=ServletActionContext.getServletContext().getRealPath("/")+"upload";
        
        //文件唯一名称
        fileOnlyName = "用freemarker导出的Word文档_"+sb+".doc";
        
        //文件名称
        fileName="用freemarker导出的Word文档.doc";
        
        /** 生成word */
        WordUtil.createWord(dataMap, "news.ftl", filePath, fileOnlyName);
        
        return "createWordSuccess";
    }
    
    
 /**
  * @Desc:下载生成的word文档,入口,用来跳转至struts XML配置
  * @Author:张轮
  * @Date:2014-1-22下午07:36:29
  * @return
  */
    public String dowloadWord() {
        /** 先判断文件是否已生成  */
        try {
         //解决中文乱码
         filePath = URLDecoder.decode(filePath, "UTF-8");
         fileOnlyName = URLDecoder.decode(fileOnlyName, "UTF-8");
         fileName = URLDecoder.decode(fileName, "UTF-8");
         
         //如果文件不存在,则会跳入异常,然后可以进行异常处理
            new FileInputStream(filePath + File.separator +  fileOnlyName);
        } catch (Exception e) {
         e.printStackTrace();
         return "error";
        }
        return "dowloadWord";
    }
    
    /**
     * @Desc:下载生成的word文档
     * 该方法是struts.xml文件中的: <param name="inputName">wordFile</param> 中自动对应的get方法,该方法自动调用
     * @Author:张轮
     * @Date:2014-1-22下午07:36:29
     * @return 返回最终生成的word文档 文件流
     */
    public InputStream getWordFile(){
        try {
         //解决中文乱码
         fileName = URLDecoder.decode(fileName, "UTF-8");
         
            /** 返回最终生成的word文件流  */
            return new FileInputStream(filePath + File.separator + fileOnlyName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


 public String getFilePath() {
  return filePath;
 }


 public void setFilePath(String filePath) {
  this.filePath = filePath;
 }


 public String getFileName() {
  return fileName;
 }


 public void setFileName(String fileName) {
  this.fileName = fileName;
 }


 public String getFileOnlyName() {
  return fileOnlyName;
 }


 public void setFileOnlyName(String fileOnlyName) {
  this.fileOnlyName = fileOnlyName;
 }

}

 

 

struts2配置文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <package name="word" namespace="/" extends="struts-default">
  <action name="createWord" class="com.lun.action.WordAction" method="createWord">
   <result name="createWordSuccess" type="redirectAction">
    <param name="actionName">dowloadWord</param>  
    <param name="filePath">${filePath}</param>
    <param name="fileOnlyName">${fileOnlyName}</param>
    <param name="fileName">${fileName}</param>
    <param name="encode">true</param>
   </result>
  </action>
  <action name="dowloadWord" class="com.lun.action.WordAction" method="dowloadWord">
   <result name="dowloadWord" type="stream">
    <param name="contentDisposition">attachment;filename="${fileName}"</param>
    <param name="inputName">wordFile</param>
    <param name="encode">true</param>
   </result>
   <result name="error">/error.jsp</result>
  </action>
 </package>
</struts>

页面调用如下:

<input type="button" onclick="javascript:window.location.href='createWord.action'" value="生成Word"/>

 

3、   注意

1、        编辑word模板时,${string} 标签最好是手动一次性输入完毕,或者使用记事本统一将整个${string}编辑好之后,粘贴至word里边。

也就是说,不要在word里首先打完 ${ } 之后,又从其它地方把 string 字符串粘贴至 { } 之间,这样在 word 转化为 xml时,解析会有问题,freemarker解析时,会报错。

将${} 和 string 分开录入word,另存为xml后,后果将如下:

 

2、        如果word里有需要循环表格列,也就是横向循环表格时,建议尽量改为循环行,纵向循环,这样可以减少对 ftl 文件的 list标签插入,缩减工作量。

分享到:
评论

相关推荐

    FreeMarker生成word文件

    以下是关于如何使用FreeMarker生成Word文件的一些关键知识点: 1. **FreeMarker模板语言**:FreeMarker使用一种简单的模板语言,允许开发者通过定义变量和控制结构(如循环和条件语句)来动态地插入数据。在模板中...

    利用FreeMarker生成word文件例子

    ### 使用FreeMarker生成Word文档 1. **配置FreeMarker**:首先,需要在项目中引入FreeMarker的依赖,例如通过Maven或Gradle添加对应的依赖库。然后,配置FreeMarker的环境,包括设置模板目录、缓存策略等。 2. **...

    使用freemarker生成word文档,源代码+jar包+说明文档及注意事项

    使用freemarker生成word ,并集成struts2 同时生成及下载文档 资料附有Java源代码和自己总结的使用说明及注意事项 大至预览如下: 1、用word编辑好模板 普通字符串替换为 ${string} 表格循环用标签 姓名:${...

    java利用freemarker生成word.pdf

    这个步骤是使用 Freemarker 库来生成 Word 文档的核心步骤。 在 Demo 中,我们可以看到,首先,我们需要引入 Freemarker 库的相关类,然后创建一个 Configuration 对象,并设置默认的编码为 UTF-8。接着,我们可以...

    springboot中使用freemarker动态生成word文档,以及使用POI导出自定义格式Excel

    Springboot项目中: 1. 使用Apache POI 3.9 自定义样式导出Excel文件...2. 使用freemarker动态生成word .doc文档(带图片Word以及复杂格式word) 详细说明见个人博客及 github: https://github.com/DuebassLei/excel-poi

    java+Freemarker生成word

    在Java中使用Freemarker生成Word文档的过程主要包括以下几个步骤: 1. **环境配置**:首先,你需要在项目中引入必要的库,包括Apache POI用于处理Word文档,以及Freemarker库。在Maven项目中,可以在pom.xml文件中...

    freemarker 生成word,支持一个单元格生成多张图片

    最后,使用FreeMarker的`Template.process()`方法生成处理后的文本,然后用Apache POI将这个文本写入Word文档的相应位置,完成图片的插入。记得关闭所有打开的流和资源,以防止内存泄漏。 总的来说,通过FreeMarker...

    freemarker生成word,pdf转word,pdf插入图片

    freemarker根据模板ftl生成word,pdf格式转word,pdf指定位置插入图片

    Freemarker导出word示例,包括jfreechart图表

    总的来说,这个示例提供了使用Freemarker和JFreechart生成带有动态图表的Word文档的方法。这对于报告生成、数据分析或其他需要可视化的场景非常有用,因为它允许开发者将动态数据与专业设计的文档模板相结合,创建出...

    freemarkerdemo 生成word 插入图片

    服务器端的Java代码负责处理业务逻辑,准备数据模型,然后使用Freemarker将这些数据模型渲染成Word文档。这个过程中可能需要使用到HTTP请求和响应,以及文件流处理,以便将生成的Word文档发送到客户端。 5. **模板...

    Java中使用 FreeMarker 生成pdf盖章合同文件

    本篇文章将深入探讨如何在Java中使用FreeMarker生成带有盖章的PDF合同文件。 首先,让我们了解FreeMarker的基本概念。FreeMarker是一个基于模板的语言,它与Java代码分离,允许开发者用简单的模板语法来表示数据。...

    freemarker根据word模板生成word的完整示例

    在这个示例中,我们将深入探讨如何使用Freemarker根据XML模板生成Word文档。 首先,你需要了解Freemarker的基本概念。Freemarker是一个基于模板的语言,它的核心是模板文件,模板文件中包含了一系列控制结构(如...

    用freemarker生成word.zip

    以上步骤详细解释了如何利用FreeMarker和Apache POI在Java中生成包含多张图片的Word文档。实际操作中,可能还需要根据具体需求调整模板、处理图片编码、调整文档样式等。在解压后的"用freemarker生成word.zip"文件中...

    freemarker生成word

    4. 使用FreeMarker生成Word文档步骤: - 加载模板:使用`Configuration`类加载`.ftl`模板文件。 - 设置数据模型:创建一个数据模型对象,将需要插入模板的数据放入。 - 创建Word文档:使用FreeMarker的`Template`...

    freemarker生成word文件,后端java代码

    freemarker生成word文件 1.模板制造 先用word编辑好格式样式。 另存为xml。 直接将后缀改为ftl格式,模板就生成了。 2.freemarker文件中的运算判断方式,可自行查询百度

    SpringBoot_Freemarker生成Word_多个表格+两层嵌套循环

    SpringBoot_Freemarker生成Word_多个表格+两层嵌套循环; 步骤说明: 1.用Microsoft Office Word打开word原件;将文档中需要动态生成的内容,替换为属性名 ${name} 2.另存为,选择保存类型Word 2003 XML 文档(*....

    java Freemarker生成word

    下面是使用 Java Freemarker 生成 Word 文档的详细步骤和知识点。 Step 1: 准备 Word 模板 在生成 Word 文档之前,需要准备一个 Word 模板。这个模板应该包含需要动态生成的内容,例如姓名、日期、表名、表中数据...

    freemarker模板生成word文档完整代码

    最近在做一个出卷系统,需要通过试卷模板从数据库中抽取题目,然后按照模板的样式生成完整的试卷,包括试卷格式的排版和图片的写入。这是用freemarker模板生成word文档。里面包括完整代码和所需jar包。

    关于Freemarker生成word的使用 java生成word

    转载的文章,利用freemarker生成word,可适用于(有附表的或无附表)word模板填充动态数据。

Global site tag (gtag.js) - Google Analytics