日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET使用NPOI读取Word模板并替换关键字并下载

發布時間:2023/12/1 asp.net 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET使用NPOI读取Word模板并替换关键字并下载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

NPOI 是 POI?項目的 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2組件文檔的項目。

使用 NPOI 你就可以在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文檔進行讀寫

NPOI下載地址:http://npoi.codeplex.com/

以下代碼僅供參考,請根據實際需求進行修改。

public MemoryStream Export(){string filepath = Server.MapPath("/word/xmxx.docx");using (FileStream stream = File.OpenRead(filepath)){XWPFDocument doc = new XWPFDocument(stream);//遍歷段落foreach (var para in doc.Paragraphs){ReplaceKey(para);}//遍歷表格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);}}}}using (MemoryStream ms = new MemoryStream()){doc.Write(ms);return ms;}}}private void ReplaceKey(XWPFParagraph para){BLL.XmxxBLL XmxxBLL = new BLL.XmxxBLL();Model.Xmxx model = new Model.Xmxx();model = XmxxBLL.GetModel(20);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){if (text.Contains("{$xmxx." + p.Name + "}")){text = text.Replace("{$xmxx." + p.Name + "}", TM.Common.StringHelper.ToString(p.GetValue(model, null)));}}runs[i].SetText(text, 0);}}protected void Button1_Click(object sender, EventArgs e){using (MemoryStream ms = Export()){Response.ContentType = "application/vnd.ms-word";Response.ContentEncoding = Encoding.UTF8;Response.Charset = "";Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("123.doc", Encoding.UTF8));Response.BinaryWrite(Export().GetBuffer());Response.End();}}

?

轉載于:https://www.cnblogs.com/tangxueyang/p/4741430.html

總結

以上是生活随笔為你收集整理的.NET使用NPOI读取Word模板并替换关键字并下载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。