C#将内容导出到Word到指定模板
生活随笔
收集整理的這篇文章主要介紹了
C#将内容导出到Word到指定模板
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
昨天做了下導(dǎo)入導(dǎo)出Excel文件,今天研究了下導(dǎo)出Word文件。 從網(wǎng)上找了半天才找到了一個能導(dǎo)出到指定模板的,在這里總結(jié)下。
導(dǎo)出模板原理就是利用的替換占位符。
我這里先建立好了一個模板,
接下來寫代碼進行導(dǎo)出,
前端就一段AJAX調(diào)用,這里我就不寫了,直接上后端代碼,看下面:
/// <summary>/// 導(dǎo)出Word文件/// </summary>/// <returns></returns> [HttpPost]public ActionResult LeadWord(){#region 動態(tài)創(chuàng)建DataTable數(shù)據(jù)DataTable tblDatas = new DataTable("Datas");DataColumn dc = null;//賦值給dc,是便于對每一個datacolumn的操作dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));dc.AutoIncrement = true;//自動增加dc.AutoIncrementSeed = 1;//起始為1dc.AutoIncrementStep = 1;//步長為1dc.AllowDBNull = false;// dc = tblDatas.Columns.Add("name", Type.GetType("System.String"));dc = tblDatas.Columns.Add("sex", Type.GetType("System.String"));dc = tblDatas.Columns.Add("age", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str1", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str2", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str3", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str4", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str5", Type.GetType("System.String"));dc = tblDatas.Columns.Add("str6", Type.GetType("System.String"));dc = tblDatas.Columns.Add("remark", Type.GetType("System.String"));DataRow newRow;newRow = tblDatas.NewRow();newRow["name"] = "張三";newRow["sex"] = "男";newRow["age"] = "11";newRow["str1"] = "字符串1";newRow["str2"] = "字符串2";newRow["str3"] = "字符串3";newRow["str4"] = "字符串4";newRow["str5"] = "字符串5";newRow["str6"] = "字符串6";newRow["remark"] = "備注一下";tblDatas.Rows.Add(newRow);#endregion#region word要替換的表達式和表格字段的對應(yīng)關(guān)系Dictionary<string, string> dic = new Dictionary<string, string>();dic.Add("$name$", "name");dic.Add("$sex$", "sex");dic.Add("$age$", "age");dic.Add("$str1$", "str1");dic.Add("$str2$", "str2");dic.Add("$str3$", "str3");dic.Add("$str4$", "str4");dic.Add("$str5$", "str5");dic.Add("$str6$", "str6");dic.Add("$remark$", "remark");#endregionstring tempFile = "~/Content/Word/temp.doc";string saveFile = "~/Content/Word/1.doc";WordUtility w = new WordUtility(tempFile, saveFile);w.GenerateWord(tblDatas, dic, null);return Content("ok");}Helper Class(WordUtility.cs)
using System; using System.Collections.Generic; using System.Data; using Word = Microsoft.Office.Interop.Word; using System.IO; using System.Windows.Forms; using System.Runtime.Remoting.Contexts;namespace Headfree.DefUI {/// <summary>/// 使用替換模板進行到處word文件/// </summary>public class WordUtility{private object tempFile = null;private object saveFile = null;private static Word._Document wDoc = null; //word文檔private static Word._Application wApp = null; //word進程private object missing = System.Reflection.Missing.Value;public WordUtility(string tempFile, string saveFile){tempFile=System.Web.HttpContext.Current.Server.MapPath(tempFile);saveFile = System.Web.HttpContext.Current.Server.MapPath(saveFile); this.tempFile = Path.Combine(Application.StartupPath, @tempFile);this.saveFile = Path.Combine(Application.StartupPath, @saveFile);}/// <summary>/// 模版包含頭部信息和表格,表格重復(fù)使用/// </summary>/// <param name="dt">重復(fù)表格的數(shù)據(jù)</param>/// <param name="expPairColumn">word中要替換的表達式和表格字段的對應(yīng)關(guān)系</param>/// <param name="simpleExpPairValue">簡單的非重復(fù)型數(shù)據(jù)</param>public bool GenerateWord(DataTable dt, Dictionary<string, string> expPairColumn, Dictionary<string, string> simpleExpPairValue){if (!File.Exists(tempFile.ToString())){return false;}try{wApp = new Word.Application();wApp.Visible = false;wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing);wDoc.Activate();// 當前文檔置前bool isGenerate = false;if (simpleExpPairValue != null && simpleExpPairValue.Count > 0)isGenerate = ReplaceAllRang(simpleExpPairValue);// 表格有重復(fù)if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0)isGenerate = GenerateTable(dt, expPairColumn);if (isGenerate)wDoc.SaveAs(ref saveFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);DisposeWord();return true;}catch (Exception ex){ return false;}}/// <summary>/// 單個替換 模版沒有重復(fù)使用的表格/// </summary>/// <param name="dc">要替換的</param>public bool GenerateWord(Dictionary<string, string> dc){return GenerateWord(null, null, dc);}private bool GenerateTable(DataTable dt, Dictionary<string, string> expPairColumn){try{int tableNums = dt.Rows.Count;Word.Table tb = wDoc.Tables[1];tb.Range.Copy();Dictionary<string, object> dc = new Dictionary<string, object>();for (int i = 0; i < tableNums; i++){dc.Clear();if (i == 0){foreach (string key in expPairColumn.Keys){string column = expPairColumn[key];object value = null;value = dt.Rows[i][column];dc.Add(key, value);}ReplaceTableRang(wDoc.Tables[1], dc);continue;}wDoc.Paragraphs.Last.Range.Paste();foreach (string key in expPairColumn.Keys){string column = expPairColumn[key];object value = null;value = dt.Rows[i][column];dc.Add(key, value);}ReplaceTableRang(wDoc.Tables[1], dc);}return true;}catch (Exception ex){DisposeWord(); return false;}}private bool ReplaceTableRang(Word.Table table, Dictionary<string, object> dc){try{object replaceArea = Word.WdReplace.wdReplaceAll;foreach (string item in dc.Keys){object replaceKey = item;object replaceValue = dc[item];table.Range.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing,ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing,ref missing);}return true;}catch (Exception ex){DisposeWord();return false;}}private bool ReplaceAllRang(Dictionary<string, string> dc){try{object replaceArea = Word.WdReplace.wdReplaceAll;foreach (string item in dc.Keys){object replaceKey = item;object replaceValue = dc[item];wApp.Selection.Find.Execute(ref replaceKey, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref missing,ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing,ref missing);}return true;}catch (Exception ex){ return false;}}private void DisposeWord(){object saveOption = Word.WdSaveOptions.wdSaveChanges;wDoc.Close(ref saveOption, ref missing, ref missing);saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;wApp.Quit(ref saveOption, ref missing, ref missing); //關(guān)閉Word進程 }} }?
好了,代碼就這么多,來看下導(dǎo)出效果吧:
ZJ。。。
?
轉(zhuǎn)載于:https://www.cnblogs.com/shuai7boy/p/6984941.html
總結(jié)
以上是生活随笔為你收集整理的C#将内容导出到Word到指定模板的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL创建用户与授权方法
- 下一篇: 自己做的一个固定大小对象内存池,效率大概