姓名 | 張三 | 性別 | 男 |
籍貫 | 浙江 | 學歷 | 本科 |
家庭地址 | 浙江省未名市未名區未名街 | ||
電話 | 12345678 | 省份證號 | 123456789012345678 |
假設我們需要將客戶的信息導成word文檔,其格式類似上面這樣的。 我們可以先准備一個word模板,格式如下
姓名 | {name} | 性別 | {sex} |
籍貫 | {provinve} | 學歷 | {education} |
家庭地址 | {address} | ||
電話 | {telephone} | 省份證號 | {cardno} |
這里要替換的內容,我們可以定義成數據庫中對應的字段,這里為了看上去清晰將要替換的內容用{字段}來代替,你也可以用其他你想要
的方式來定義。
接下來看實現的方式(記得首先在引用中添加相應的組件哦!)
public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ReplaceToExcel(); } /// <summary> /// 替換word中的文本,並導出word /// </summary> protected void ReplaceToExcel() { Word.Application app = null; Word.Document doc = null; //將要導出的新word文件名 string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc"; string physicNewFile = Server.MapPath(DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc"); try { app = new Word.Application();//創建word應用程序 object fileName = Server.MapPath("template.doc");//模板文件 //打開模板文件 object oMissing = System.Reflection.Missing.Value; doc = app.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //構造數據 Dictionary<string, string> datas = new Dictionary<string, string>(); datas.Add("{name}", "張三"); datas.Add("{sex}", "男"); datas.Add("{provinve}", "浙江"); datas.Add("{address}", "浙江省杭州市"); datas.Add("{education}", "本科"); datas.Add("{telephone}", "12345678"); datas.Add("{cardno}", "123456789012345678"); object replace = Word.WdReplace.wdReplaceAll; foreach (var item in datas) { app.Selection.Find.Replacement.ClearFormatting(); app.Selection.Find.ClearFormatting(); app.Selection.Find.Text = item.Key;//需要被替換的文本 app.Selection.Find.Replacement.Text = item.value;//替換文本 //執行替換操作 app.Selection.Find.Execute( ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } //對替換好的word模板另存為一個新的word文檔 doc.SaveAs(physicNewFile, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); //准備導出word Response.Clear(); Response.Buffer = true; Response.Charset = "utf-8"; Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.ContentType = "application/ms-word"; Response.End(); } catch (System.Threading.ThreadAbortException ex) { //這邊為了捕獲Response.End引起的異常 } catch (Exception ex) { } finally { if (doc != null) { doc.Close();//關閉word文檔 } if (app != null) { app.Quit();//退出word應用程序 } //如果文件存在則輸出到客戶端 if (File.Exists(physicNewFile)) { Response.WriteFile(physicNewFile); } } } }