用 c# 來操作WORD的經驗總結

來源:互聯網
上載者:User

標籤:exists   val   sum   isnull   包括   總結   com   路徑   find   

最近在做一個程式,需要在程式中對Word內容做些處理。從網上查了很多資料,發現,許多都是重複的。更有許多知識,根本沒有講到。為了以後使用方便。將所有的這些知識,加以總結,以備後來人使用。

1、引用

    需要引用 COM庫:Microsoft word 11.0 Object Library. 不同的版本,會有不同的版本號碼。

   如 2010版Office 就是 Microsoft word 14.0 Object Library.

2、引用相應的名字空間:

    using Microsoft.Office.Core;

    using word = Microsoft.Office.Interop.Word;

3、開啟一個已存在的word文檔

public void OpenDocFile(string docName)        {                    object oMissing = System.Reflection.Missing.Value;  //一個編程時需要經常使用的一個參數        word.ApplicationClass wordapp = null;   //這是WORD程式,在這個程式下,可以同時開啟多個文檔,盡量不要同時開啟多個Word程式,否則會出錯的。        word.Document doc = null;  //第一個需要開啟的WORD文檔        word.Document doc2 = null;  //另一個需要開啟的WORD文檔         wordapp = new word.ApplicationClass();        wordapp.Visible = true; //所開啟的WORD程式,是否是可見的。             object docObject = docName;  //由於COM操作中,都是使用的 object ,所以,需要做一些轉變                                if (File.Exists(docName))   // 如果要開啟的檔案名稱存在,那就使用doc來開啟             {                doc = wordapp.Documents.Add(ref docObject, ref oMissing, ref oMissing, ref oMissing);                doc.Activate();   //將當前檔案設定為使用中文件                ParagraphsCount = doc.Content.Paragraphs.Count;   //此文檔中,段落的數量,也就是這個文檔中,有幾個段落。            }            else   //如果檔案名稱不存在,那就使用doc2來開啟            {                doc2 = wordapp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);                DocFileName = docName;                doc2.Activate();   //將當前檔案設定為使用中文件              }                          }

 4、擷取某一段的具體常值內容

public string Paragraph(int index)        {            word.Paragraph   para;              para = doc.Content.Paragraphs[index];   ///這是一個設定對應的某一段                          return para.Range.Text;        }

 5、DOC內容藉助於剪貼簿的複製與粘貼

/// <summary>        /// 將doc某一段的內容複寫到剪貼簿上        /// </summary>        /// <param name="index">段的序號</param>        public void CopyParagraph( int index)        {            word.Paragraph para;            para = doc.Content.Paragraphs[index];            para.Range.Copy();                }        /// <summary>        /// 將剪貼簿的內容粘貼到doc2文檔中        /// </summary>        public void PasteParagraph()        {            if (doc2 != null)            {                word.Paragraph para = doc2.Content.Paragraphs.Add(ref oMissing);                try                {                    para.Range.Paste();                    para.Range.InsertParagraphBefore();//添加一次斷行符號                }                catch (Exception e)                {                    throw e;                }            }        }

6、關閉WORD程式和文檔

/// <summary>        /// 關閉 word程式        /// </summary>        public void CloseWord()        {            if (wordapp != null)            {                if (doc != null)                {                    word._Document docc = doc as word._Document;                    docc.Close(ref oMissing, ref oMissing, ref oMissing);                }                if (doc2 != null)                {                    word._Document docc = doc2 as word._Document;                    docc.Close(ref oMissing, ref oMissing, ref oMissing);                }                wordapp.Quit(ref oMissing, ref oMissing, ref oMissing);            }        }

7、替換文檔中的內容

/// <summary>        /// 替換文檔中的內容        /// </summary>        /// <param name="oldString">原有內容</param>        /// <param name="newString">替換後的內容</param>        public void Replace(string oldString, string newString)        {            doc2.Content.Find.Text = oldString;            object FindText, ReplaceWith, ReplaceAll;            FindText = oldString;            ReplaceWith = newString;            ReplaceAll = word.WdReplace.wdReplaceAll;            doc2.Content.Find.Execute(ref FindText,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref ReplaceWith,                                       ref ReplaceAll,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing,                                       ref oMissing);        }

以上,如果要替換其中的斷行符號符為空白格,可以這樣使用

Replace(“^p”,"");

就可以了,這一點,與在WORD中使用的替換功能是一樣的。

8、儲存文檔內容

/// <summary>        /// 儲存word文檔(只儲存doc2)        /// </summary>        public void SaveDocFile()        {            if (doc2 != null)            {                if (!string.IsNullOrEmpty(DocFileName))                {                    object docname = DocFileName;//要儲存的檔案名稱,包括路徑                    Replace("^p^p", "^p");                    doc2.SaveAs2(ref docname,                                  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,                                 ref oMissing);                }            }                }

9、在複製過程中,如果文檔中有表格,那麼,上面所使用的複製方法,一般會報錯。“"此方法或屬性無效,因為 對象涉及表格行尾"。出現的原因就是因為 Paragraphs 只能是文字內容不能包括表格,在WORD中,表格是另一類重要的文件類型。其實在表格中,每一個儲存格都是一個獨立的段落。所以,如果文檔中有表格,那麼文檔的 doc.Content.Paragraphs.Count 數量會增加很多。在複製過程中,可以採用下面的方法來複製。

 

/// <summary>        /// 複製文檔的內容,從開始到結束(包括結束與開始的段落)的段落內容。        /// </summary>        /// <param name="first">開始的段落號</param>        /// <param name="next">結束的段落號</param>        public void CopyParagraph2(int first,int next)        {            word.Range range = doc.Range();            word.Paragraph para1;            para1 = doc.Content.Paragraphs[first];            range.Start = para1.Range.Start;            word.Paragraph para2;            para2 = doc.Content.Paragraphs[next];            range.End = para2.Range.End;            range.Copy();                }

 

在這個複製過程中,重建立立了一個地區 word.Range range = doc.Range(); 這個地區包括文檔的所有內容。
然後根據段落的要求分別設定地區的Start  和 End ,如果在 Start  和 End 之間有一個表格的話,那麼表格也會被正確複製過去.

 

用 c# 來操作WORD的經驗總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.