你的位置:首页 > ASP.net教程

[ASP.net教程]NOPI读取Word模板并保存


可以在 程序包管理器控制台中输入
PM> Install-Package NPOI
会下载最新版本NPOI
----------------------------引用了NPOI--------------------------------
 
public static void Export()    {      string filepath = HttpContext.Current.Server.MapPath("~/simpleTable.docx");      Test tt = new Test { name = "cjc", age = 29 };      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);      }    }

模板:

111

结果:

222