C#操作Word之 根據標籤名清除標籤內容

iDotNetSpace發表於2009-02-05

程式碼已經測試過了,try catch語句你自己加,記得要保證出錯之後能夠釋放資源

執行此操作後,被操作標籤會被去掉

 

Code

        private void button1_Click(object sender, EventArgs e)
        {
            ClearBookMarkFromDoc(@"C:\test.doc","a");
        }


        public void ClearBookMarkFromDoc(string FilePath, string BkName)
        {
            object filepath = FilePath as object;
            object missing = Type.Missing;
            object bjTrue = true as object;

            //建立word.application應用
            Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document myWordDoc = myWordApp.Documents.Open(ref filepath, 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);

            Microsoft.Office.Interop.Word.Range bmRange = default(Microsoft.Office.Interop.Word.Range);

            Microsoft.Office.Interop.Word.Bookmarks bkmrs = myWordDoc.Bookmarks;

            object bkIndex = BkName as object;
            Microsoft.Office.Interop.Word.Bookmark bkm = bkmrs.get_Item(ref bkIndex);

            textBox1.Text = bkm.Name;
            bkm.Range.Text = string.Empty;

            myWordDoc.Save();
            myWordDoc.Close(ref objTrue, ref missing, ref missing);
            myWordApp.Quit(ref objTrue, ref missing, ref missing);
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-545380/,如需轉載,請註明出處,否則將追究法律責任。

相關文章