FreeMarker生成word

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

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

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

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

dataMap.put("listUser",list);

步骤1:

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

 

 

步骤2:

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

步骤3:

打开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="1、" />
                            <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

posted @ 2014-12-01 23:13  惩罚者  阅读(4925)  评论(0编辑  收藏  举报