1.新增专案
2.载入组件DocX (用NUGET载入)
3.using Xceed.Words.NET;
1.测试1.docx 里面写[$t1$],等等把[$t1$]做替换.
private static void 黑大_来源是一个值(){ string fileName = @"e:\测试1.docx"; using (DocX document = DocX.Load(fileName)) { //替换 document.ReplaceText("[$t1$]", "yayaya"); string fileNamexx = @"e:\测试1_RESULT.docx"; document.SaveAs(fileNamexx); }}
2.测试2.docx 里面写[$today$] [$name$] [$addr$] [$amount$],等等把[$$]做替换.
private static void 黑大2_来源是dictionary() { string fileName = @"e:\测试2.docx"; Dictionary<string, string> dct = new Dictionary<string, string>() { { "today", DateTime.Today.ToString("yyyy-MM-dd") }, { "name", "大光头" }, { "addr", "幸福" }, { "amount", "没卖" } }; using (DocX document = DocX.Load(fileName)) { foreach (string key in dct.Keys) { document.ReplaceText("[$" + key + "$]", dct[key]); } string fileNamexx = @"e:\测试2_RESULT.docx"; document.SaveAs(fileNamexx); } }
3.测试3:来源改成DATATABLE
测试3.docx 里面写[$today$] [$name$] [$addr$] [$amount$],等等把[$$]做替换.
using System;using Xceed.Words.NET;using System.IO;private void 黑大_来源是datatable() { string tmpFileName = DateTime.Now.ToString("yyyyMMddHHmmssFFF"); string fileNamexx = @"E:\" + tmpFileName + ".docX";//2 save string srcFileName = @"e:\测试3.docx"; AccessDB AccDB = new AccessDB(); string strSQL = "select today='t1' ,name='love',addr='金门',amount='3.333' "; AccDB.OpenConnection(); AccDB.GetDataAdapter(strSQL); AccDB.sDataSet = AccDB.GetDataSet(); AccDB.CloseConnection(); using (DocX document = DocX.Load(srcFileName)) { foreach (System.Data.DataColumn dc in AccDB.sDataSet.Tables[0].Columns) { string key = dc.ColumnName; document.ReplaceText("[$" + key + "$]", AccDB.sDataSet.Tables[0].Rows[0][key].ToString()); } document.SaveAs(fileNamexx); } byte[] buff = File.ReadAllBytes(fileNamexx); File.Delete(fileNamexx); Response.Clear(); Response.ContentType = "application/octet-stream";//word OK Response.AddHeader("content-disposition", "attachment;filename=RESULT.docx"); Response.BinaryWrite(buff); Response.End(); }