根據指定Word模板生成Word文件


最近業務需要批量打印准考證信息

1、根據Table數據進行循環替換,每次替換的時候只替換Word中第一個Table的數據,

2、每次替換之后將Word中第一個Table數據進行復制,將復制Table和上次替換的Table合並為一個Table。由於替換后的Table中不存在占位符,只有復制的Table中存在占位符,所有每次循環根據占位符替換最新數據就可以達到批量生成Word的目的了

Word模板:

批量替換后的Word:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using System.Data;

namespace WebApplication1
{

    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)
        {

            this.tempFile = Path.Combine(HttpContext.Current.Server.MapPath("Word"), @tempFile);
            this.saveFile = Path.Combine(HttpContext.Current.Server.MapPath("Temp"), @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()))
            {
                HttpContext.Current.Response.Write("<script>alert('" + string.Format("{0}模版文件不存在,請先設置模版文件。", tempFile.ToString()) + "');</script>");
                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)
            {
                HttpContext.Current.Response.Write("<script>alert('" + "生成失敗" + ex.Message + "');</script>");
                return false;
            }
        }

        /// <summary>
        /// 單個替換 模版沒有重復使用的表格
        /// </summary>
        /// <param name="dc">要替換的</param>
        public bool GenerateWord(Dictionary<string, string> dc)
        {
            return GenerateWord(null, null, dc);
        }

        /// <summary>
        /// 替換文件
        /// </summary>
        /// <param name="dt">要更新的數據</param>
        /// <param name="expPairColumn">當前要替換的數據字典</param>
        /// <returns></returns>
        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();
                HttpContext.Current.Response.Write("<script>alert('" + "生成模版里的表格失敗。" + ex.Message + "');</script>");
                return false;
            }
        }
        /// <summary>
        /// 替換文件
        /// </summary>
        /// <param name="table">當前Word中表格中要替換的Table</param>
        /// <param name="dc">要替換的數據字典</param>
        /// <returns></returns>
        private bool ReplaceTableRang(Word.Table table, Dictionary<string, object> dc)
        {
            try
            {
                
                object replaceArea = Word.WdReplace.wdReplaceAll;
                //替換Word中指定Table的字段信息
                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();
                HttpContext.Current.Response.Write("<script>alert('" + string.Format("{0}模版中沒有找到指定的要替換的表達式。{1}", tempFile, ex.Message) + "');</script>");
                return false;
            }
        }
        /// <summary>
        /// 替換不重復數據
        /// 當前表格中的所有信息都替換
        /// </summary>
        /// <param name="dc">替換的數據字典</param>
        /// <returns></returns>
        private bool ReplaceAllRang(Dictionary<string, string> dc)
        {
            try
            {
                object replaceArea = Word.WdReplace.wdReplaceAll;
                //替換整個Word文檔里面的字段信息
                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)
            {
                HttpContext.Current.Response.Write("<script>alert('" + string.Format("{0}模版中沒有找到指定的要替換的表達式。{1}", tempFile, ex.Message) + "');</script>");
                return false;
            }
        }
        /// <summary>
        /// 釋放資源
        /// </summary>
        private void DisposeWord()
        {
            object saveOption = Word.WdSaveOptions.wdSaveChanges;
            //釋放資源並且保持Word
            wDoc.Close(ref saveOption, ref missing, ref missing);

            saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;

            wApp.Quit(ref saveOption, ref missing, ref missing); //關閉Word進程
        }
    }
}


調用:

           //Word模板路徑
            string word_ModelName = "SmallList - 副本.doc";
            //生成后的Word文件路徑
            string word_SaveName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".doc";
            //重復替換字典數據
            //根據字典的Key字段,找到表格中的對應列,然后根據字典的value字段,找到Word中對應要替換的字段
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("Name", "Name");
            dict.Add("Age", "Age");
            dict.Add("ShenFenNumber", "ShenFenNumber");
            dict.Add("ZhunKaoNumber", "ZhunKaoNumber");
            dict.Add("Gender", "Gender");

            //不重復數據字典
            //Key為Word中需要替換的占位符  Value為替換后的內容
            Dictionary<string, string> dictNo = new Dictionary<string, string>();
            dictNo.Add("ExamName", "《計算機導論》");
            dictNo.Add("ExamTime", "120分鍾");
            WordUtility createWord = new WordUtility(word_ModelName, word_SaveName);
            createWord.GenerateWord(GetDT(), dict, dictNo);

 注:本文部分信息參考其他網絡

 


免責聲明!

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



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