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