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

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: |||超大  

NPOI 是 POI 项目的 .NET 版本。POI是一个开源的java读写Excel、Word等微软OLE2组件文档的项目。

使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写

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

以下代码仅供参考,请根据实际需求进行修改。

publicMemoryStream Export()

{stringfilepath = Server.MapPath("/word/xmxx.docx");using(FileStream stream =File.OpenRead(filepath))

{

XWPFDocument doc=newXWPFDocument(stream);//遍历段落foreach(varparaindoc.Paragraphs)

{

ReplaceKey(para);

}//遍历表格vartables =doc.Tables;foreach(vartableintables)

{foreach(varrowintable.Rows)

{foreach(varcellinrow.GetTableCells())

{foreach(varparaincell.Paragraphs)

{

ReplaceKey(para);

}

}

}

}using(MemoryStream ms =newMemoryStream())

{

doc.Write(ms);returnms;

}

}

}PRivatevoidReplaceKey(XWPFParagraph para)

{

BLL.XmxxBLL XmxxBLL=newBLL.XmxxBLL();

Model.Xmxx model=newModel.Xmxx();

model= XmxxBLL.GetModel(20);stringtext =para.ParagraphText;varruns =para.Runs;stringstyleid =para.Style;for(inti =0; i < runs.Count; i++)

{varrun =runs[i];

text=run.ToString();

Type t=model.GetType();

PropertyInfo[] pi=t.GetProperties();foreach(PropertyInfo pinpi)

{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);

}

}protectedvoidButton1_Click(objectsender, 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();

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航