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

本文介绍了一种使用C#编程语言动态填充Word文档模板并导出的方法。该方法通过读取特定路径下的.docx文件,利用Apache POI库遍历文档中的段落和表格进行关键字替换,实现数据填充。最后将填充后的文档输出到内存流中,并通过HTTP响应下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值