可以在 程式包管理器控制臺中輸入PM> Install-Package NPOI會下載最新版本NPOI----------------------------引用了NPOI-------------------------------- public static void Export() { s... ...
可以在 程式包管理器控制臺中輸入
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); } }
模板:
結果: