利用NVelocity 模版生成文本文件

namespace Common
{
    public class Tools
    {
        public string Process(string content, int startIndex, int length)
        {
            string result = content.Substring(startIndex, length);
            return result;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Commons.Collections;
using System.IO;
using System.Data;
using Common;
using NVelocity.App;
using NVelocity.Runtime;

namespace NVelocity
{  
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID", typeof(string));
            dt1.Columns.Add("Name", typeof(string));
            dt1.Columns.Add("Add", typeof(string));      
            dt1.Rows.Add("001", "小明", "我家住黄土高坡上");
            dt1.Rows.Add("002", "小红", "我住在黄土高坡下");

            DataTable dt2 = new DataTable();
            dt2.Columns.Add("ID", typeof(string));
            dt2.Columns.Add("Name", typeof(string));
            dt2.Columns.Add("Score", typeof(string));         
            dt2.Rows.Add("001", "数学", 11);
            dt2.Rows.Add("001", "语文", 12);
            dt2.Rows.Add("001", "英语", 13);
            dt2.Rows.Add("002", "数学", 21);
            dt2.Rows.Add("002", "语文", 22);
            dt2.Rows.Add("002", "英语", 23);

            Tools tools = new Tools();

            VelocityEngine vltEngine = new VelocityEngine();//模板引擎实例化
            ExtendedProperties ep = new ExtendedProperties();//模板引擎参数实例化
            ep.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");//指定资源的加载类型
            ep.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "f:\Template");//指定资源的加载路径   
            ep.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");//输出格式
            ep.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");//输出格式
            vltEngine.Init(ep);

            Template template = vltEngine.GetTemplate("Temp.txt");//加载模板
            VelocityContext vltContext = new VelocityContext(); //当前的数据信息载体集合
            vltContext.Put("Table1", dt1);
            vltContext.Put("Table2", dt2);
            vltContext.Put("Tools", tools);

            StringWriter vltWriter = new StringWriter();
            template.Merge(vltContext, vltWriter);

            Console.Write(vltWriter.ToString());

            Console.ReadLine();
        }
    }
}

模版:

我是开头

#foreach($user1 in $Table1.Rows)
$user1.Name
$Tools.Process($user1.Add, 0, 7)
#foreach($user2 in $Table2.Rows)
#if($user2.ID == $user1.ID)
$user2.Name $user2.Score
#end
#end

--------------------我是记录分隔符--------------
#end

我是结尾

输出结果:

原文地址:https://www.cnblogs.com/siso/p/3691557.html