C#读WORD文档的类(转,并修改)

/*

   需事先:项目/添加引用/COM,选择“Microsoft Word 11.0 object Library”,并“确定”

*/

using System;
using System.Collections.Generic;
using System.Text;

namespace MyWordApp
{
    public class MyWordClass
    {
        private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic;
        private Microsoft.Office.Interop.Word.Document oDoc;
        public MyWordClass()
        {
            oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
        }
        public Microsoft.Office.Interop.Word.Document Document
        {
            get
            {
                return this.oDoc;
            }
        }
        public Microsoft.Office.Interop.Word.ApplicationClass Application
        {
            get
            {
                return this.oWordApplic;
            }
        }
        /**/
        /// <summary>  
        /// 设置Word文档是否可视  
        /// </summary>  
        /// <param name="InEnabled">boolean</param>  
        private void SetVisible(Boolean InEnabled)
        {
            oWordApplic.Visible = InEnabled;
        }
        /**/
        /// <summary>  
        /// 在垃圾回收时,在任务管理器中还存在当前操作的WORD的进程  
        /// 查阅资料,必须在另一个方法中在调用GC才可以真正的清除掉,当前的进程  
        /// </summary>  
        private void GCForQuit()
        {
            object missing = System.Reflection.Missing.Value;
            oWordApplic.Quit(ref missing, ref missing, ref missing);
            if (oDoc != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                oDoc = null;
            }
            if (oWordApplic != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic);
                oWordApplic = null;
            }
            GC.Collect();
        }
        /**/
        /// <summary>  
        /// 打开一个空的Word模板  
        /// </summary>  
        public bool Open()
        {
            bool result = false;
            try
            {
                object missing = System.Reflection.Missing.Value;
                oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                oDoc.Activate();
                result = true;
            }
            catch
            {
                this.Quit();
                //throw ( new Exception() );  
            }
            return result;
        }
        public void Close()
        {
            object isSave = false;
            object missing = System.Reflection.Missing.Value;
            oDoc.Close(ref isSave, ref missing, ref missing);
        }
        /**/
        /// <summary>  
        /// 退出  
        /// </summary>  
        public void Quit()
        {
            GCForQuit();
            GC.Collect();
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName.ToUpper() == "WINWORD")
                {
                    p.Kill();
                }
            }
        }
        /**/
        /// <summary>  
        /// 打开指定的Word文档  
        /// </summary>  
        /// <param name="strFileName">指定的Word文档</param>  
        public bool Open(string strFileName)
        {
            return this.Open(strFileName, true);
        }
        /**/
        /// <summary>  
        /// 打开指定的Word文档并判断是否显示  
        /// </summary>  
        /// <param name="strFileName">指定的Word文档</param>  
        /// <param name="isEnabled">显示与否</param>  
        public bool Open(string strFileName, bool isEnabled)
        {
            bool result = false;
            if (strFileName == null || strFileName == "") return result;
            try
            {
                object fileName = strFileName;
                object readOnly = false;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;
#if OFFICEXP  
            oDoc                = oWordApplic.Documents.Open(ref fileName, ref missing,ref readOnly,   
                                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,   
                                    ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing);
#else
                oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
#endif
                oDoc.Activate();
                oWordApplic.Visible = isEnabled;
                result = true;
            }
            catch
            {
                this.Quit();
                //throw ( new Exception() );  
            }
            return result;
        }
        /** <summary>  
        /// 定位到文档开头  
        /// </summary>  
        public void GoToTheBeginning( )  
        {  
            object missing    = System.Reflection.Missing.Value;  
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;  
            oWordApplic.Selection.HomeKey ( ref unit, ref missing );  
              
        }   
        /** <summary>  
        /// 定位到文档结尾  
        /// </summary>  
        public void GoToTheEnd( )  
        {  
            object missing    = System.Reflection.Missing.Value;  
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;  
            oWordApplic.Selection.EndKey ( ref unit, ref missing );  
        }   
        /** <summary>  
        /// 定位到首段  
        /// </summary>  
        /// <returns></returns>  
        public Microsoft.Office.Interop.Word.Paragraph GoToFirstParagraph()  
        {  
            return this.oWordApplic.Selection.Paragraphs.First;  
        }  
        /** <summary>  
        /// 定位到尾段  
        /// </summary>  
        /// <returns></returns>  
        public Microsoft.Office.Interop.Word.Paragraph GoToEndParagraph()  
        {  
            return this.oWordApplic.Selection.Paragraphs.Last ;  
        }  
        /** <summary>  
        /// 向后定位到指定段落  
        /// </summary>  
        /// <param name="para"></param>  
        /// <param name="count"></param>  
        public void GoToNextParagraph(ref Microsoft.Office.Interop.Word.Paragraph para, ref object count)  
        {  
            para.Next(ref count) ;  
        }  
        /** <summary>  
        /// 向前定位到指定段落  
        /// </summary>  
        /// <param name="para"></param>  
        /// <param name="count"></param>  
        public void GoToPreviousParagraph(ref Microsoft.Office.Interop.Word.Paragraph para, ref object count)  
        {  
            para.Previous( ref count ) ;  
        }


        public Boolean ExecuteFind(Microsoft.Office.Interop.Word.Find find)  
        {  
            return ExecuteFind( find, find.Text, Type.Missing, Type.Missing );  
        }
        public Boolean ExecuteFind(Microsoft.Office.Interop.Word.Find find, string strFindText)  
        {  
            return ExecuteFind( find, strFindText, Type.Missing, Type.Missing );  
        }  
        public Boolean ExecuteFind(
             Microsoft.Office.Interop.Word.Find find, string strFindText, Object wrapFind, Object forwardFind)  
        {  
            // Simple wrapper around Find.Execute:  
              
            Object findText ;  
            Object matchCase = Type.Missing;  
            Object matchWholeWord = Type.Missing;  
            Object matchWildcards = Type.Missing;  
            Object matchSoundsLike = Type.Missing;  
            Object matchAllWordForms = Type.Missing;  
            Object forward = forwardFind;  
            Object wrap = wrapFind;  
            Object format = Type.Missing;  
            Object replaceWith = Type.Missing;  
            Object replace = Type.Missing;  
            Object matchKashida = Type.Missing;  
            Object matchDiacritics = Type.Missing;  
            Object matchAlefHamza = Type.Missing;  
            Object matchControl = Type.Missing;  
        
            if ( ( strFindText == "" )||( strFindText == string.Empty ) )  
                findText = find.Text;  
            else
                findText = strFindText;  
            find.ClearFormatting();  
            return find.Execute( ref findText, ref matchCase, ref matchWholeWord,   
                ref matchWildcards, ref matchSoundsLike, ref matchAllWordForms,   
                ref forward, ref wrap, ref format, ref replaceWith, ref replace,   
                ref matchKashida, ref matchDiacritics, ref matchAlefHamza,   
                ref matchControl );  
        }


        public Boolean FindInSelection(Microsoft.Office.Interop.Word.Selection Selection, string strFindText)   
        {  
                          
            return this.ExecuteFind( Selection.Find,strFindText,System.Type.Missing,System.Type.Missing );  
        }
        public Boolean FindInSelection(Microsoft.Office.Interop.Word.Selection Selection, string strFindText, Object wrapFind, Object forwardFind)   
        {  
                          
            return this.ExecuteFind( Selection.Find, strFindText, wrapFind, forwardFind );  
        }
        public Boolean FindInRange(Microsoft.Office.Interop.Word.Range range, string strFindText)   
        {  
            Boolean blnReturn =this.ExecuteFind( range.Find, strFindText, Type.Missing, Type.Missing );  
            range.Select();  
            return blnReturn;  
        }  
    
        public long FindFromCurr2End( string strFindText,long currPosition )   
        {  
            //int intFound        = 0;  
            Object start = currPosition;  
            Object end            = this.oDoc.Characters.Count;
            Microsoft.Office.Interop.Word.Range rngDoc = oDoc.Range(ref start, ref end);
            Microsoft.Office.Interop.Word.Find fnd = rngDoc.Find;  
            fnd.ClearFormatting();  
            fnd.Forward        = true;  
            fnd.Text        = strFindText;  
            ExecuteFind( fnd );  
            if/*while*/ ( fnd.Found )  
            {
                //rngDoc.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;  
                //rngDoc.Font.Bold    = 600;
                return rngDoc.Start;
                //intFound++;  
                //ExecuteFind( fnd );  
            }
            return -1;
            //MessageBox.Show( String.Format( "lorem found {0} times.", intFound ), "FindInLoopAndFormat" );  
        }

        /**/
        /// <summary>  
        /// 插入文本操作,所有的打开与保存操作在外部执行  
        /// </summary>  
        /// <param name="strText"></param>  
        public void InsertText(string strText)
        {
            oWordApplic.Selection.TypeText(strText);
        }

        public int GetTableCount()
        {
            return oDoc.Tables.Count;
        }
        public int GetTableCols(int n)
        {
            return oDoc.Tables[n].Columns.Count;
        }
        public int GetTableRows(int n)
        {
            return oDoc.Tables[n].Rows.Count;
        }
        public string GetCellText(int nTable, int row, int col)
        {
            return oDoc.Tables[nTable].Cell(row, col).Range.Text;
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值