.net core 使用NPOI填充Word模板導出Word

  最近工作用到在Word模板插入數據庫數據,導出一個帶數據的Word文件,想起來之前操作Word都是用微軟提供的Microsoft.Office.Interop.Word,而在最新的..NET CORE 2.0則沒發現什麼適用的方法,於是想起了POI移植到.NET平臺的NPOI,於是在網上查找了下在.NET CORE 平臺下NPOI的情況,大致瞭解下NPOI在.NET CORE下一直是有位民間大神Savorboard開發的,直到CORE 2.0版本後.在NuGet中搜索DotNetCore.NPOI,得到下圖,2.0後使用DotNetCore.NPOI,在2.0之前都是由使用大神開發的較早的版本Savorboard.NPOI.CORE.OOXML.更多關於NPOI的介紹參考博文:http://www.cnblogs.com/savorboard/p/dotnetcore-npoi.html 

  NPOI本人熟悉的不多,本次用到的功能就是根據實際數據填充進預先的Word模板實現一個特殊特定格式Word的導出,在這我選擇使用1.0.2版本的DotNetCore.NPOI,因爲在1.2版本本人在項目中使用時候經常就無法實例化XWPFDocument對象,使用的是標準的word 2007新建的docx文件,找了很久原因最後在降級到版本1.0.2得到解決。

  功能比較簡單,在這貼上NPOI工具類

    /// <summary>
    /// 作者:jomz
    /// </summary>
    public class NpoiHeplper
    {
        /// <summary>
        /// 輸出模板docx文檔(使用字典)
        /// </summary>
        /// <param name="tempFilePath">docx文件路徑</param>
        /// <param name="outPath">輸出文件路徑</param>
        /// <param name="data">字典數據源</param>
        public static void Export(string tempFilePath,string outPath,Dictionary<string,string> data)
        {
            using (FileStream stream = File.OpenRead(tempFilePath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍歷段落                  
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKey(para, data);
                }
                //遍歷表格      
                foreach (var table in doc.Tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKey(para, data);
                            }
                        }
                    }
                }
                //寫文件
                FileStream outFile = new FileStream(outPath, FileMode.Create);
                doc.Write(outFile);
                outFile.Close();
            }
        }
        private static void ReplaceKey(XWPFParagraph para, Dictionary<string,string> data)
        {
            string text = "";
            foreach (var run in para.Runs)
            {
                text = run.ToString();
                foreach (var key in data.Keys)
                {
                    //$$模板中數據佔位符爲$KEY$
                    if (text.Contains($"${key}$"))
                    {
                        text = text.Replace($"${key}$", data[key]);
                    }
                }
                run.SetText(text, 0);
            }
        }


        /// <summary>
        /// 輸出模板docx文檔(使用反射)
        /// </summary>
        /// <param name="tempFilePath">docx文件路徑</param>
        /// <param name="outPath">輸出文件路徑</param>
        /// <param name="data">對象數據源</param>
        public static void ExportObjet(string tempFilePath, string outPath, object data)
        {
            using (FileStream stream = File.OpenRead(tempFilePath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍歷段落                  
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKeyObjet(para, data);
                }
                //遍歷表格      
                foreach (var table in doc.Tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKeyObjet(para, data);
                            }
                        }
                    }
                }
                //寫文件
                FileStream outFile = new FileStream(outPath, FileMode.Create);
                doc.Write(outFile);
                outFile.Close();
            }
        }
        private static void ReplaceKeyObjet(XWPFParagraph para, object model)
        {
            string text = "";
            Type t = model.GetType();
            PropertyInfo[] pi = t.GetProperties();
            foreach (var run in para.Runs)
            {
                text = run.ToString();
                foreach (PropertyInfo p in pi)
                {
                    //$$模板中數據佔位符爲$KEY$
                    string key = $"${p.Name}$";
                    if (text.Contains(key))
                    {
                        try
                        {
                            text = text.Replace(key, p.GetValue(model, null).ToString());
                        }
                        catch (Exception ex)
                        {
                            //可能有空指針異常
                            text = text.Replace(key, "");
                        }
                    }
                }
                run.SetText(text, 0);
            }
        }

    }

  使用介紹,本工具類可根據字典數據源或者對象數據源導出標準的docx格式word,不考慮word排版問題,只考慮數據填充,排版由word模板使用office自行製作。

ExportObjet方法傳入word模板對象地址tempFilePath,導出到地址outPath,以及類數據源data,通過反射獲取字段匹配word模板中對應的$key$名稱去替換其值達到最後效果。同理
Export則使用字典作爲數據源。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章