NOPI讀取Word模板並儲存

風靈使發表於2018-08-04
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;

namespace WebDemo
{
    public partial class DocTest : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Export();
        }

        public static void Export()
        {
            string filepath = HttpContext.Current.Server.MapPath("~/file/simpleTable.docx");
            Test tt = new Test { name = "南通軟體工程師", age = 18 };
            using (FileStream stream = File.OpenRead(filepath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍歷段落                  
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKey(para, tt);
                }                    

                //遍歷表格      
                var tables = doc.Tables;
                foreach (var table in tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKey(para, tt);
                            }
                        }
                    }
                }

                FileStream out1 = new FileStream(HttpContext.Current.Server.MapPath("~/simpleTable" + DateTime.Now.Ticks + ".docx"), FileMode.Create);
                doc.Write(out1);
                out1.Close();
            }
        }


        private static void ReplaceKey(XWPFParagraph para, object model)
        {
            string text = para.ParagraphText;
            var runs = para.Runs;
            string styleid = para.Style;
            //for (int i = 0; i < runs.Count; i++)
            //{
            //    var run = runs[i];
            //    text = run.ToString(); 
            //    Type t = model.GetType();
            //    PropertyInfo[] pi = t.GetProperties();
            //    foreach (PropertyInfo p in pi)
            //    {
            //        //$$與模板中$$對應,也可以改成其它符號,比如{$name},務必做到唯一
            //        if (text.Contains("$" + p.Name + "$"))
            //        {
            //            text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString());
            //        }
            //    } 
            //    runs[i].SetText(text, 0);
            //}


                text = String.Join("", runs.Select(x => x.Text));
                Type t = model.GetType();
                PropertyInfo[] pi = t.GetProperties();
                foreach (PropertyInfo p in pi)
                {
                    //$$與模板中$$對應,也可以改成其它符號,比如{$name},務必做到唯一
                    if (text.Contains("$" + p.Name + "$"))
                    {
                        text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString());
                    }
                }

                int length = runs.Count();
                for (int j = (length - 1); j >= 0; j--)
                {
                     para.RemoveRun(j);
                }

                //直接呼叫XWPFRun的setText()方法設定文字時,在底層會重新建立一個XWPFRun,把文字附加在當前文字後面,
                //所以我們不能直接設值,需要先刪除當前run,然後再自己手動插入一個新的run。
                para.InsertNewRun(0).SetText(text, 0);
        }
    }

    public class Test
    {
        public string name { get; set; }
        public int age { get; set; }
    }
}

如圖:

這裡寫圖片描述


這裡寫圖片描述

相關文章