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

相關文章
相關標籤/搜索