word模板導出的幾種方式:第一種:占位符替換模板導出(只適用於word中含有表格形式的)


1.占位符替換模板導出(只適用於word中含有表格形式的):

/// <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 = tempFile;// Path.Combine(Application.StartupPath, @tempFile);
            this.saveFile = saveFile;// Path.Combine(Application.StartupPath, @saveFile);
        }

        /// <summary>
        /// 模版包含頭部信息和表格,表格重復使用
        /// </summary>
        /// <param name="dt">重復表格的數據</param>
        /// <param name="expPairColumn">word中要替換的表達式和表格字段的對應關系</param>
        /// <param name="simpleExpPairValue">簡單的非重復型數據</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);

                // 表格有重復
                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>
        /// 單個替換 模版沒有重復使用的表格
        /// </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;

                for (int j = 1; j <= wDoc.Tables.Count; j++)
                {
                    Word.Table tb = wDoc.Tables[j];

                    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[j], 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[j], 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); //關閉Word進程
        }
    }

  demo:

 #region 動態創建DataTable數據
                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;//起始為1
                dc.AutoIncrementStep = 1;//步長為1
                dc.AllowDBNull = false;//
                dc = tblDatas.Columns.Add("NO", Type.GetType("System.String"));//////1
                DataRow newRow;
                newRow = tblDatas.NewRow();
                newRow["NO"] = info.NO;////////房屋座落地址 2--info實體類


                tblDatas.Rows.Add(newRow);
                #endregion
                #region word要替換的表達式和表格字段的對應關系
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("$id$", "NO");//////////3
                #endregion
                string tempFile = "~/Doc/doc.doc";
                string saveFile = "~/Doc/" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".doc";
                WordUtility w = new WordUtility(tempFile, saveFile);
                w.GenerateWord(tblDatas, dic, null);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM