c# word操作篇,解決字串長度超過255就不能替換的問題

@ 小浩發表於2018-12-25

本文使用的是Microsoft.Office.Interop.Word元件,必須在系統安裝了office相關元件的條件下進行,在com裡面找到Microsoft  Word 16.0 Object Library並引用。

問題:使用c#操作word替換佔位符的時候,當要替換的字串超過一定的長度,就會提示“字串參量過長”,搜尋發現,替換的最大長度為255字元。

以220個字串為例,執行替換工作。

         //構造資料
        Dictionary<string, string> datas = new Dictionary<string, string>() { { "{name}", "張三" }, { "{sex}", "男" }, { "{provinve}", "浙江" } };
        //模板檔案
        object path = Server.MapPath("/Template/template.docx");
        //生成檔案
        string physicNewFile = Server.MapPath("/createdfile/" + Guid.NewGuid().ToString() + ".docx");
        /// <summary>
        /// 根據模板生成替換檔案並下載
        /// </summary>
        /// <param name="path">檔案/模板地址</param>
        /// <param name="datas">需要替換的key:value集合</param>
        /// <param name="physicNewFile">生成檔案地址</param>
        public void ReplaceToWord(object path, Dictionary<string, string> datas, string physicNewFile)
        {
            Microsoft.Office.Interop.Word.Application app = null;
            Microsoft.Office.Interop.Word._Document doc = null;
            object oMissing = System.Reflection.Missing.Value;
            try
            {
                app = new Microsoft.Office.Interop.Word.Application();
                object fileName = path;
                //開啟模板檔案                 
                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);

                object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                foreach (var item in datas)
                {
                    app.Selection.Find.Replacement.ClearFormatting();
                    app.Selection.Find.ClearFormatting();
                    if (item.Value.Length > 220)
                        FindAndReplaceLong(app, item.Key, item.Value);
                    else
                        FindAndReplace(app, item.Key, item.Value);
                }

                //對替換好的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 (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    //關閉word文件
                    doc.Close(ref oMissing, ref oMissing, ref oMissing);
                    doc = null;
                }
                if (app != null)
                {
                    //退出word應用程式
                    app.Quit(ref oMissing, ref oMissing, ref oMissing);
                    app = null;
                }
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
                //如果檔案存在則輸出到客戶端
                if (System.IO.File.Exists(physicNewFile))
                {
                    Response.WriteFile(physicNewFile);
                }
            }
        }
        /// <summary>
        /// 根據字串長度執行替換操作
        /// </summary>
        /// <param name="wordApp">當前word程式</param>
        /// <param name="findText">佔位符(key)</param>
        /// <param name="replaceText">替換字串(值)</param>
        public  void FindAndReplaceLong(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
        {
            int len = replaceText.ToString().Length;   //要替換的文字長度
            int cnt = len / 220;                    //不超過220個字
            string newstr;
            object newStrs;
            if (len < 220)   //小於220字直接替換
            {
                FindAndReplace(wordApp, findText, replaceText);
            }
            else
            {
                for (int i = 0; i <= cnt; i++)
                {
                    if (i != cnt)
                        newstr = replaceText.ToString().Substring(i * 220, 220) + findText;  //新的替換字串
                    else
                        newstr = replaceText.ToString().Substring(i * 220, len - i * 220);    //最後一段需要替換的文字
                    newStrs = newstr;
                    FindAndReplace(wordApp, findText, newStrs);                              //進行替換
                }
            }
        }
        /// <summary>
        /// 執行替換操作
        /// </summary>
        /// <param name="wordApp">當前word程式</param>
        /// <param name="findText">佔位符(key)</param>
        /// <param name="replaceText">替換字串(值)</param>
        public  void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
        {
            //object oMissing = System.Reflection.Missing.Value;
            object matchCase = true;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllWordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object read_only = false;
            object visible = true;
            object replace = 2; //object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
            object wrap = 1;
            wordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceText,
                ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
            // wordApp.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);
        }

Asp.Net操作Word內容

如果要正常操作Word Com元件的話,必須要給使用者賦上足夠的許可權的,

1、執行Dcomcnfg.exe 

2、元件服務――計算機――我的電腦――DCOM配置――找到microsoft word 文件 
3、點選屬性 
4、選擇“安全性” 
5、選定“使用自定義訪問許可權”和“使用自定義啟動許可權” 
6、分別編輯許可權,新增ASPNET,VS Developers,Debugger User //不一定
7、選擇“身份標識”,在選定“互動式使用者” 即可 (關鍵步驟)必須
8、在Web.config里加 <identity impersonate="true"/>

 

 

參考連結:http://www.cnblogs.com/riddly/p/9231719.html

相關文章