VS使用NPOI替换word模板中的关键字

使用NPOI替换word模板中的关键字

  • 简介
    • 思路
      • 模板实例
      • 引入NPOI程序扩展
      • 代码实现
      • 使用实例
      • 结果实例
      • 请多指教

简介

由于项目需求,需要根据现有的word模板,进行批量生成word报表,为了方便,选用的是 NPOI (NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目)来实现。本次用的版本是NPOI 2.3.0.0,版本不同写法会有差别。

思路

NPOI提供操作word文档的方法也比较简单。
替换模板中关键字的实现思路大致是:

  1. 获取具有关键字的模板word文档(关键字可以自己定义,需要具有唯一性和可读性);
  2. 获取文档中的所有段落Paragraphs(表格中的单元格内容也属于段落);
  3. 遍历段落,找到关键字并进行替换(表格需要先遍历单元格,再遍历单元格中的段落);
  4. 生成新的文档;

模板实例

本次实例是用VS控制台程序进行测试,需要在项目路径下新建文件夹来存放模板文件和结果文件。
模板文件的存放位置为:…\bin\Debug\Templates
生成的文件存放位置为:…\bin\Debug\GoalFiles
实例模板中的关键字有四个:

关键字 说明
{$project} 项目名称
{$Name} 负责人名字
{$Date} 日期
{$Dep} 部门

VS使用NPOI替换word模板中的关键字_第1张图片

引入NPOI程序扩展

下载NPOI的DLL包(在此不贴下载链接),在项目中添加引用:

1.ICSharpCode.SharpZipLib.dll
2.NPOI.dll
3.NPOI.OOXML.dll
4.NPOI.OpenXml4Net.dll //根据DONET的版本选择
5.NPOI.OpenXmlFormats.dll

代码实现

右键项目,添加一个WordTemplateHelper类,在其中写方法。

  public class WordTemplateHelper
    {
        /// 
        /// NPOI操作word
        /// 
        /// 模板路径
        /// 保存路径
        /// 关键字集合
        public static void WriteToPublicationOfResult(string TemplatePath,string SavePath, Dictionary<string, string> keywords)
        {
            FileStream fs = new FileStream(TemplatePath, FileMode.Open, FileAccess.Read);
            XWPFDocument document = new XWPFDocument(fs);
            foreach (var table in document.Tables)
            {
                foreach (var row in table.Rows)
                {
                    foreach (var cell in row.GetTableCells())
                    {
                        ReplaceKeyWords(cell.Paragraphs, keywords);//替换表格中的关键字
                    }
                }
            }
            ReplaceKeyWords(document.Paragraphs, keywords);//替换模板中非表格的关键字
            FileStream output = new FileStream(SavePath, FileMode.Create);
            document.Write(output);
            fs.Close();
            fs.Dispose();
            output.Close();
            output.Dispose();
        }
        /// 
        /// 遍历段落,替换关键字
        /// 
        /// 段落
        /// 关键字集合
        public static void ReplaceKeyWords(IList<XWPFParagraph> Paragraphs, Dictionary<string, string> keywords)
        {
            foreach (var item in keywords)
            {
                foreach (var para in Paragraphs)
                {
                    string oldtext = para.ParagraphText;
                    if (oldtext == "")  continue;
                    string temptext = para.ParagraphText;
                    if (temptext.Contains("{$" + item.Key + "}"))  temptext = temptext.Replace("{$" + item.Key + "}", item.Value);
                    para.ReplaceText(oldtext, temptext);
                }
            }
           
        }
        /// 
        /// 格式化关键字集合
        /// 
        /// 泛型对象
        /// 关键字集对象
        /// 
        public static Dictionary<string, string> getProperties<T>(T t)
        {
            Dictionary<string, string> keywords = new Dictionary<string, string>();
            if (t == null)
            {
                return keywords;
            }
            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            if (properties.Length <= 0)
            {
                return keywords;
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    keywords.Add(name,value.ToString());
                }
                else
                {
                    getProperties(value);
                }
            }
            return keywords;
        }


    }

使用实例

        static void Main(string[] args)
       {
           string TemplatePath1 = @"Templates/Template1.docx";//模板1路径
           string SavePath1 = @"GoalFiles/Template1.docx";//根据模板1生成的文件路径
           //关键字内容
           var ParamTemplate1 = new
           {
               Project = "Word模板关键字替换",
               Name = "Duke",
               Date = DateTime.Now.ToString("yyyy年MM月dd日"),
               Dep = "研发部" 
           };
           WordTemplateHelper.WriteToPublicationOfResult(TemplatePath1, SavePath1, WordTemplateHelper.getProperties(ParamTemplate1));

       }

结果实例

VS使用NPOI替换word模板中的关键字_第2张图片

请多指教

功能虽然实现,但是解释的可能不大清楚,写博客记录一下开发经历,如有错误,请多指教。

你可能感兴趣的:(VS使用NPOI替换word模板中的关键字)