FreeMarker生成word

FreeMarker生成word数据填充是经过,Map填充。java

Map dataMap = new HashMap<String, Object>();数据库

List<User> list=new List<User>();apache

dataMap.put("title", "测试");dom

dataMap.put("listUser",list);工具

步骤1:测试

   编辑word模块,模板配置好后。另存为word 2003 XML格式,并选择“仅保存数据”。lua

 

 

步骤2:spa

   将生成好的xml打开,里面的内容复制到新建的ftl文件,将ftl文件放到项目中做为模板.net

步骤3:code

打开ftl文件,替换要填充的数据  如要提货 “Fan” 打开后输入  ${userName},”userName“是Map里面的key的名字,freemarker数据填充是经过Map的

 

步骤4:
 
JAVA代码:
 
package cn.uway.lte.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 导出WORD工具类
 * 
 * @author 
 *     @时间        2014-10-9
 */
public class DocumentUtil extends CommonUtil
{
    /**
     * 配置信息对象
     */
    private Configuration configuration = null;
    
    public DocumentUtil() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
    }

    /**
     * 生成word并下载
     * @param sc 
     * @param dataMap 模板数据
     * @param request 请求
     * @param response 响应输出下载流
     */
    @SuppressWarnings("rawtypes")
    public void createDoc(ServletContext sc,Map dataMap,HttpServletRequest request,HttpServletResponse response) {
        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。能够重servlet,classpath,数据库装载,
        configuration.setServletContextForTemplateLoading(sc,"WEB-INF/template");
        Template t = null;
        try {
            // test.ftl为要装载的模板
            t = configuration.getTemplate("evaluateTemplate.ftl");
            t.setEncoding("utf-8");
        } catch (IOException e) {
            logger.error("生成模板出错,错误信息:",e);
        }

        String strPath=returnSaveDir(request);
        String fileSaveName = StringUtils.join(new String[] {
                java.util.UUID.randomUUID().toString(), ".doc"});
        String lastFileName=strPath+fileSaveName;
        // 输出文档路径及名称
        File outFile = new File(lastFileName);
        Writer out = null;
        
        try {
            out = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(outFile), "utf-8"));
        } catch (Exception e) {
            logger.error("生成模板出错,错误信息:",e);
        }
        
        try {
            t.process(dataMap, out);
            out.flush();
            out.close();
            File file = new File(lastFileName);
            FileUtil.downloadFile(file, response);
            // 若是存在就删除
            if (file.exists()) {
                file.delete();
            }

        } catch (TemplateException e) {
            logger.error("生成模板出错,错误信息:",e);
        } catch (IOException e) {
            logger.error("生成模板出错,错误信息:",e);
        }

    }
    
    /**
     * 返回文件生成位置
     * 
     * @author fanhy
     * @param request
     * @return
     */
    private  String returnSaveDir(HttpServletRequest request){
        // 文件保存位置,当前项目下的upload/import
        String uploadDir = "upload" + File.separatorChar + "import"+ File.separatorChar;

        String ctxDir = request.getSession().getServletContext().getRealPath(String.valueOf(File.separatorChar));
        if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
            ctxDir = ctxDir + File.separatorChar;
        }
        // 获取建立路径
        File savePath = new File(ctxDir + uploadDir);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        String saveDirectory = ctxDir + uploadDir;
        return saveDirectory;
    }

    
}

 

FTL模板:

if语句使用:

根据条件展现某一块的数据

<#if (AllNetWork="true")>
                <w:p wsp:rsidR="00A635F3" wsp:rsidRDefault="00A635F3" wsp:rsidP="00A635F3">
                    <w:pPr>
                        <w:pStyle w:val="1" />
                        <w:listPr>
                            <w:ilvl w:val="0" />
                            <w:ilfo w:val="2" />
                            <wx:t wx:val="一、" />
                            <wx:font wx:val="Times New Roman" />
                        </w:listPr>
                        <w:ind w:first-line-chars="0" />
                        <w:outlineLvl w:val="1" />
                    </w:pPr>

</#if>

非空判断

${time!}

<#if rscpList.startTime??>
    ${rscpList.startTime?string('yyyy-MM-dd HH:mm:ss')}
</#if>

 

 

图片插入:image二进制图片流

<w:pict>
<w:binData w:name="wordml://03000001.jpg">${image}</w:binData>
<v:shape id="_x0000_i1025" type="#_x0000_t75" style="width:450.75pt;height:200pt">
<v:imagedata src="${"wordml://03000001.jpg"}" />
</v:shape>
</w:pict>

 

 

List填充数据表格:

在这里表头没有加入太长了,只是从第二行开始生成数据!

<#list RNCList as RNCList>
                    <w:tr wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidTr="006F59E7">
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1382" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>
                                    <#if RNCList.startTime??>
                                    ${RNCList.startTime?string('yyyy-MM-dd HH:mm:ss')}
                                    </#if>
                                    </w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1382" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>${RNCList.cityName!}</w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1383" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>${RNCList.rncName!}</w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1383" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>${RNCList.rscpAvg}</w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1383" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>${RNCList.ecnoAvg}</w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                        <w:tc>
                            <w:tcPr>
                                <w:tcW w:w="1383" w:type="dxa" />
                                <w:shd w:val="clear" w:color="auto" w:fill="auto" />
                            </w:tcPr>
                            <w:p wsp:rsidR="003A2EA1" wsp:rsidRPr="006F59E7" wsp:rsidRDefault="00345453" wsp:rsidP="006F59E7">
                                <w:pPr>
                                    <w:jc w:val="left" />
                                </w:pPr>
                                <w:proofErr w:type="spellStart" />
                                <w:r wsp:rsidRPr="006F59E7">
                                    <w:t>${RNCList.badcellRate}</w:t>
                                </w:r>
                                <w:proofErr w:type="spellEnd" />
                            </w:p>
                        </w:tc>
                    </w:tr>
</#list>

 

 

 

参考:http://blog.csdn.net/lun379292733/article/details/18673081