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