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