机器环境: .net framework 1.1 + office 2003 + window XP我要做的是,在程序里操作WORD.下面的程序是在window application 下,没有问题.但是在web application下,网页程序执行不成功,进度条一直在走,但是很长时间也没有反应.也不报错 Word.ApplicationClass wordObj = new Word.ApplicationClass();
wordObj.Visible = true;
object wordPath = @"c:\ly.doc";
object optional=Missing.Value;
object readOnly = false;
object isVisible = true;
Word.Document wordDoc = wordObj.Documents.Open(ref wordPath,ref optional,ref readOnly,ref optional,
ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,
ref optional,ref isVisible,ref optional,ref optional,ref optional);

object first=0;
object last=wordDoc.Characters.Count;
//Response.Write(wordDoc.Characters.Count);
wordDoc.Range(ref first,ref last).Select();
Thread.Sleep(3000);
wordDoc.Range(ref first,ref last).Cut();
//string getWord = wordDoc.Range(ref first,ref last).Text;
//MessageBox.Show(getWord);
Thread.Sleep(3000);
object fileName = @"c:\newly.doc";
wordDoc.SaveAs(ref fileName,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,
ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,ref optional,
ref optional,ref optional); // 现在像好用户一样,使用 Quit 方法进行清理

object saveChanges = true;
object originalFormat = Missing.Value;
object routeDocument = Missing.Value;

wordObj.Quit(ref saveChanges, ref originalFormat, ref routeDocument); 不知道怎么修改?请大家指点.

解决方案 »

  1.   

    路径怎么都用本地的,应该使用URL地址呀。
    另外,权限是否足够。ASP.NET应用程序执行时以ASPNET用户来执行的。
      

  2.   

    我是想做打开一个本地的WORD文档.在web application里,我用了身份模拟,asp.net的权限不够,我用了管理员组的一个成员,在web.config里添加了一行 <identity impersonate="true" userName="admin" password="123456"/>
      

  3.   

    权限不足呀!把 aspnet用户加入服务器的管理员组测试一下,如果行了,那肯定是了,不过测试完成后一定要删除呀!
      

  4.   

    我用身份模拟,还不行么??一定要把aspnet放到管理员组里??
      

  5.   

    怎么在Windows下好像也不行是使用Microsoft Word 11.0 Object Library对吗?
      

  6.   

    你打开的始终是服务器上的word文档,根本就打不开客户端的,如果要操作的话,用activex控件吧
      

  7.   

    我就是要打开服务器的文档.
    我引用的是 Microsoft Word 11.0 Object Library
      

  8.   

    2003的安全级别比较高!首先确保你有足够的权限,开始-运行:dcomcnfg
    在应用程序列表框中选择“Microsoft Word 应用程序”->
    “安全性”->选择“使用自定义访问权限”,点击“编辑”按钮
    添加本地“ASPNET”用户,权限为“允许访问
      

  9.   

    用office控件行不行?我看了新思创的oa就是采用这种方法。可以对它进行很多操作。
      

  10.   

    UP
    UP
    UPUP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
    UP
      

  11.   

    http://www.cnblogs.com/wssmax/archive/2005/06/02/166729.html
    我觉得这个com控件不错。
      

  12.   

    .net下操作WORD的资料,简单理了一下,分享出来,希望对大家有所帮助。
    那时找资料主要是为了实现对WORD里的表格操作, 找到的资料都是英文的,可能有些翻译不太正确。下图是Word对像模型Application :用来表现WORD应用程序,包含其它所有对象。他的成员经常应用于整个WORD,你可以用它的属性和方法控制WORD环境。
    Document :Document对象是WORD编程的核心。当你打开打开一个已有的文档或创建一个新的文档时,就创建了一个新的Documnet对象, 新创建的Document将会被添加到Word Documents Collection。
    Selection :Selection对象是描述当前选中的区域。若选择区域为空,则认为是当前光标处。
    Rang :是Document的连续部分,根据起始字符和结束字符定义位置。
    Book:类似于Rang,但Book可以有名字并在保存Document时Book也被保存。以下代码则为打开一个WORD2003文件。        public void CreateWordDocument(string FileName)
            {
                if(FileName == "") return;
                this.thisApplication =
                    new Microsoft.Office.Interop.Word.ApplicationClass();
                thisApplication.Visible = true;
                thisApplication.Caption = "";
                thisApplication.Options.CheckSpellingAsYouType = false;
                thisApplication.Options.CheckGrammarAsYouType = false;            Object filename = FileName;
                Object ConfirmConversions = false;
                Object ReadOnly = true;
                Object AddToRecentFiles = false;            Object PasswordDocument = System.Type.Missing;
                Object PasswordTemplate = System.Type.Missing;
                Object Revert = System.Type.Missing;
                Object WritePasswordDocument = System.Type.Missing;
                Object WritePasswordTemplate = System.Type.Missing;
                Object Format = System.Type.Missing;
                Object Encoding = System.Type.Missing;
                Object Visible = System.Type.Missing;
                Object OpenAndRepair = System.Type.Missing;
                Object DocumentDirection = System.Type.Missing;
                Object NoEncodingDialog = System.Type.Missing;
                Object XMLTransform = System.Type.Missing;//            Microsoft.Office.Interop.Word.DocumentClass wordDoc =
    //                wordApp.Documents.Open(ref filename, ref ConfirmConversions,
    //                ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
    //                ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
    //                ref Encoding, ref Visible);
    //            Microsoft.Office.Interop.Word.DocumentClass wordDoc =
    //                wordApp.Documents.Open(ref filename, ref ConfirmConversions,
    //            ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
    //            ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
    //            ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog);            Microsoft.Office.Interop.Word.Document wordDoc =
                    thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
                    ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                    ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
                    ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
                    ref NoEncodingDialog, ref XMLTransform );            this.thisDocument = wordDoc;            formFields = wordDoc.FormFields;
            }关闭WORD程序程序
    Object SaveChanges = false; 
    Object OriginalFormat = System.Type.Missing; 
    Object RouteDocument = System.Type.Missing; 
    this.thisApplication.Quit( ref SaveChanges, ref OriginalFormat, ref RouteDocument ); 参考资料:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_vsto2003_ta/html/wordobject.asp
      

  13.   

    ,一个Document可能会有多个Rang对象。Rang由起始和结束字符来定他的位置。
    以下代码为先清空Document里的内容,再在第一行写入内容。
        // Clear out any existing information.
        Object start = Type.Missing;
        Object end = Type.Missing;
         Object unit = Type.Missing;
        Object count = Type.Missing;
        ThisDocument.Range(ref start, ref end). Delete(ref unit, ref count);    // Set up the header information.
        start = 0;
        end = 0;
         rng = ThisDocument.Range(ref start, ref end);
         rng.InsertBefore("Xiaopai");
         rng.Font.Name = "Verdana";
         rng.Font.Size = 16;
         rng.InsertParagraphAfter();//输入回车以下为在刚写入的内容后添加一个表格。
        object missingValue = Type.Missing; 
        object location = 8; //注:若location超过已有字符的长度将会出错。
        Word.Range rng = ThisDocument.Range(ref location, ref location);
        ThisDocument.Tables.Add(rng, 3, 4, ref missingValue, ref missingValue); 以下为在刚创建的表格里添加一行
        Word.Table tbl = ThisDocument.Tables[1]; //第一个表格为1,而不是0
        Object beforeRow = Type.Missing; 
        tbl.Rows.Add(ref beforeRow); //在表格的最后添加一行填充表格内容
        tbl.Cell(1, 1).Range.Text = "shuai"; //在表格的第一行第一列填入内容。设置单元格风格
        Word.Range rngCell; 
        rngCell = tbl.Cell(1, 2).Range; 
        rngCell.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
        rngCell.Font.Size = 8;
        rngCell.Font.Name = "Verdana";当时没找到合并单元格的方法。有谁知道的共享一下哈。参考资料:
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtocreatewordtables.asp 
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtoaddrowscolumnstowordtables.asp 
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_vsto2003_ta/html/odc_VSTWordtbl.asp 
      

  14.   

    namespace ImportExportToOffice
    {
        using System;
        using System.ComponentModel;
        using System.Data;
        using System.Windows.Forms;
        public class ImportExportToWord
        {
            private Word.ApplicationClass oWordApplic;    
            private Word.Document oDoc;        
            private const string strFileName    = @"F:\";
            private const string PostfixForWord    = @".doc";
            private const string PostfixForHtml    = @".Html";        构造函数#region 构造函数
            public ImportExportToWord()
            {
                oWordApplic = new Word.ApplicationClass();
            }
            #endregion        public Word.Document Document
            {
                get
                {
                    return this.oDoc;
                }
            }        public Word.ApplicationClass Application
            {
                get
                {
                    return this.oWordApplic;
                }    
            }         私有方法#region 私有方法        /**//// <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.Application.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>
            /// 返回保存文件的FileName
            /// </summary>
            /// <param name="strDefaultExt">要保存文件的类型</param>
            /// <param name="strFilter">文件名筛选器字符串</param>
            /// <returns>保存的路径</returns>
            private string SaveFileName( string strDefaultExt, string strFilter )
            {
                string fileName = "";
                System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog(); 
                saveFileDlg.DefaultExt    = strDefaultExt;
                saveFileDlg.Filter        = strFilter;
                if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK ) 
                    fileName = saveFileDlg.FileName;
                return fileName;
            }        /**//// <summary>
            /// 将被 SaveFileName 取代
            /// </summary>
            /// <returns></returns>
            private string SaveFileToHtmlForName()
            {
                string fileName = "";
                System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog(); 
                saveFileDlg.DefaultExt    = "Html";
                saveFileDlg.Filter        = "html文件 (*.html)|*.htm";
                if ( saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK ) 
                    fileName = saveFileDlg.FileName;
                return fileName;
            }            /**//// <summary>
            /// 保存
            /// </summary>
            private void Save( )
            {
                oDoc.Save();            
            }                #endregion         公有方法#region 公有方法        /**//// <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;
            }
            
            /**//// <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();
                    }
                }
            }
      

  15.   

    /**//// <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);
                #endif
                    oDoc.Activate();        
                    oWordApplic.Visible = isEnabled;
                    result = true;
                }
                catch
                {
                    this.Quit();
                    //throw ( new Exception() );
                }
                return result;
            }            /**//// <summary>
            /// 另存
            /// </summary>
            public bool SaveAs( )
            {
                object missing            = System.Reflection.Missing.value;
                object fileName            = SaveFileName( "doc", "doc文件 (*.doc)|*.doc" );
                return this.SaveAs( Convert.ToString( fileName ) );
            }            /**//// <summary>
            /// 另存
            /// </summary>
            /// <param name="strFileName"></param>
            public bool SaveAs( string strFileName )
            {
                bool result = false;
                if ( strFileName == null || strFileName == "" ) return result;
                try
                {
                    object missing    = System.Reflection.Missing.value;
                    object fileName = strFileName ;
                #if OFFICEXP
                    oDoc.SaveAs( ref fileName, 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 );
                #else
                    oDoc.SaveAs( ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing );
                #endif
                    result = true;
                }
                catch
                {
                    //throw( new Exception() );
                }
                finally
                {
                    this.Quit();
                }
                return result;
            }    
            /**//// <summary>
            /// 把Word文档装化为Html文件
            /// </summary>
            /// <param name="strFileName">要转换的Word文档</param>
            public bool WordToHtml( string strFileNameForWord )
            {
                string saveFileName = strFileName + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + PostfixForHtml;
                return this.WordToHtml( strFileNameForWord, saveFileName );
            }        /**//// <summary>
            /// 把Word文档装化为Html文件
            /// </summary>
            /// <param name="strFileName">要转换的Word文档</param>
            /// <param name="strSaveFileName">要生成的具体的Html页面</param>
            public bool WordToHtml( string strFileNameForWord, string strSaveFileName )
            {
                bool result = false;
                if ( strFileNameForWord == null || strFileNameForWord == "" ) return result;
                if ( this.Open( strFileNameForWord, false ) )
                {
                    try
                    {
                        Type wordType = oWordApplic.GetType();
                        // 打开文件
                        Type docsType = oWordApplic.Documents.GetType();
                        // 转换格式,另存为
                        Type docType = oDoc.GetType();
                        object saveFileName = strSaveFileName;
                        docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, oDoc, new object[]{ saveFileName, Word.WdSaveFormat.wdFormatHTML } );
                        其它格式:#region 其它格式:
                        /**////wdFormatHTML
                        ///wdFormatDocument
                        ///wdFormatDOSText
                        ///wdFormatDOSTextLineBreaks
                        ///wdFormatEncodedText
                        ///wdFormatRTF
                        ///wdFormatTemplate
                        ///wdFormatText
                        ///wdFormatTextLineBreaks
                        ///wdFormatUnicodeText
                        //-----------------------------------------------------------------------------------
                        //            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
                        //                null, oDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
                        // 退出 Word
                        //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
                        //    null, oWordApplic, null );
                        #endregion
                        result = true;
                    }
                    catch
                    {
                        //throw ( new Exception() );
                    }
                    finally
                    {
                        this.Quit();
                    }
                }
                return result;
            }
      

  16.   

    /**//// <summary>
            /// 插入文本操作,所有的打开与保存操作在外部执行
            /// </summary>
            /// <param name="strText"></param>
            public void InsertText( string strText )
            {
                oWordApplic.Selection.TypeText( strText );
            }        public void InsertText( string strText, int iNum )
            {
                for ( int i = 0; i < iNum; i++ )
                    this.InsertText( strText );
            }
            /**//// <summary>
            /// 插入文本操作
            /// </summary>
            /// <param name="strText">要保存的字符串</param>
            public bool InsertTextBySelection( string strText )
            {
                string strsavefilename = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss") + PostfixForWord;
                return this.InsertTextBySelection( strText, strsavefilename );
            }        /**//// <summary>
            /// 
            /// </summary>
            /// <param name="strText">要保存的字符串</param>
            /// <param name="strSaveFileName">保存后的doc文件名</param>
            public bool InsertTextBySelection( string strText, string strSaveFileName )
            {
                return this.InsertTextBySelection( strText, strSaveFileName, 20, 20, 0, 0, "华文仿宋" );
            }        /**//// <summary>
            /// 
            /// </summary>
            /// <param name="strText">要保存的字符串</param>
            /// <param name="strSaveFileName">保存后的doc文件名</param>
            /// <param name="leftindent">首行缩近多少</=param>
            /// <param name="size">字体大小</param>
            /// <param name="boldbi">是否粗体;1 yes, 0 no</param>
            /// <param name="paragraphalignment">对齐方式</param>
            public bool InsertTextBySelection( string strText, string strSaveFileName, float firstlineindent , int size, int boldbi,int paragraphalignment, string fontname )
            {
                bool result = false;
                if ( strText == "" || strText == null ) return result;
                if ( this.Open() )
                {
                    try
                    {
                        string[] strvalue = strText.Split( ''$'');
                        if ( strvalue.Length != 0  )
                        {
                            oWordApplic.Selection.TypeText( "今天是:"+ DateTime.Now.ToString("yyyy-MM-dd") );
                            Word.Paragraph para = this.GoToFirstParagraph();
                            para.Range.Select();
                            this.SetFontName( fontname );
                            this.SetFirstLineIndent( firstlineindent );
                            this.SetFontSize( 20 );
                            this.setBoldBi( boldbi );
                            switch ( paragraphalignment )
                            {
                                case 0 :
                                    this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphLeft);
                                    break;
                                case 1 :
                                    this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter);
                                    break;
                                case 2:
                                    this.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphRight);
                                    break;
                            }
                            int j = 0;
                            for( int i= 0; i < strvalue.Length; i++ )
                            {
                                
                                this.InsertParagraphAfterByParagraph(para,1);    //加1个空行
                                para = this.GoToEndParagraph();                 //定位到第1空行
                                this.InsertTextBeforeByParagraph( para, strvalue[i] );
                                para = this.GoToEndParagraph();
                                para.Range.Select();
                                this.setBoldBi( boldbi );                        //设置标题非粗体字
                                this.SetFontSize( size );                        //设置字体大小
                                this.SetFontName( fontname );                    //设置字体
                                j++;
                                if ( j == 9 )
                                {
                                    this.InsertText( "━━━━", 6 );
                                    j = 0;
                                }                        }
                            if ( this.SaveAs( strSaveFileName ) )
                                result = true;
                        }
                    }
                    catch
                    {
                        this.Quit();
                        //throw( new Exception() );
                    }
                }
                return result;
            }        /**//// <summary>
            /// 插入空行
            /// </summary>
            public void InsertLineBreakBySelection( )
            {
                oWordApplic.Selection.TypeParagraph();
            }        /**//// <summary>
            /// 插入指定的空行
            /// </summary>
            /// <param name="nline">行数</param>
            public void InsertLineBreakBySelection( int nline )
            {
                for ( int i = 0; i < nline; i++ )
                    this.InsertLineBreakBySelection();
            }        /**//// <summary>
            /// 换页
            /// </summary>
            public void InsertPagebreak()
            {
                object pBreak= (int)Word.WdBreakType.wdPageBreak;
                oWordApplic.Selection.InsertBreak( ref pBreak );
            }        public void InsertTextBeforeByParagraph( Word.Paragraph paragraph, string strText )
            {
                paragraph.Range.InsertBefore( strText );
            }        public void InsertTextAfterByParagraph( Word.Paragraph paragraph, string strText )
            {
                paragraph.Range.InsertAfter( strText );        }        public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph )
            {
                paragraph.Range.InsertParagraphBefore();
            }        public void InsertParagraphBeforeByParagraph( Word.Paragraph paragraph,int nLine )
            {
                for ( int i = 0; i < nLine; i++ )
                    paragraph.Range.InsertParagraphBefore();
            }        public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph )
            {
                paragraph.Range.InsertParagraphAfter();
            }        public void InsertParagraphAfterByParagraph( Word.Paragraph paragraph, int nLine )
            {
                for ( int i = 0; i < nLine; i++ )
                    paragraph.Range.InsertParagraphAfter();
            }
      

  17.   

    /**//// <summary>
            /// 数据集转换 即把DataSet转换为Word对象 
            /// </summary>
            /// <param name="ds"></param>
            public bool DataSetToWord( DataSet ds, string strFileName )
            {
                bool result = false;
                if ( ds == null ) return result;
                if ( strFileName == null || strFileName == "" ) return result;
                if ( this.Open() )
                {
                    try
                    {
                        Word.Range para = oWordApplic.Application.Selection.Paragraphs.Item(1).Range;
                        object tableBehavior    =System.Reflection.Missing.value;
                        object autoFitBehavior    =System.Reflection.Missing.value;
                        oDoc.Tables.Add( para,
                            ds.Tables[0].Rows.Count+1,    //多的一行用来表示表列
                            ds.Tables[0].Columns.Count,
                            ref tableBehavior,
                            ref autoFitBehavior );                    //填充Word表格的列标
                        for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
                        {
                            oDoc.Tables.Item(1).Cell( 1, intCol+1 ).Range.InsertBefore( ds.Tables[0].Columns[intCol].ColumnName.Trim() );
                        }
                    
                        //填充Word表格的内容
                        for( int intRow = 0; intRow < ds.Tables[0].Rows.Count; intRow++ )
                        {
                            for( int intCol = 0; intCol < ds.Tables[0].Columns.Count; intCol++ )
                            {
                                oDoc.Tables.Item(1).Cell( intRow+2, intCol+1 ).Range.InsertBefore( ds.Tables[0].Rows[intRow][intCol].ToString().Trim() );
                            }
                        }
                        //保存
                        if ( this.SaveAs( strFileName ) )
                            result = true;
                    }
                    catch
                    {
                        this.Quit();
                        //throw ( new Exception() );
                    }
                }
                return result;
            }
            
            /**//// <summary>
            /// 采用默认地址保存
            /// </summary>
            /// <param name="ds"></param>
            public bool DataSetToWord( DataSet ds )
            {
                return this.DataSetToWord( ds, strFileName + ds.Tables[0].TableName.ToString() + PostfixForWord );
            }
            /**//// <summary>
            /// 段落的对齐方式
            /// 例如:word.SetAlignment(Word.WdParagraphAlignment.wdAlignParagraphCenter)
            /// </summary>
            /// <param name="alignment"></param>
            public void SetAlignment( Word.WdParagraphAlignment alignment )
            {
                oWordApplic.Selection.ParagraphFormat.Alignment = alignment;
            }        /**//// <summary>
            /// 首行缩进
            /// </summary>
            /// <param name="fltCount">float类型的数值</param>
            public void SetFirstLineIndent( float fltCount )
            {
                oWordApplic.Selection.ParagraphFormat.FirstLineIndent = fltCount;
            }        /**//// <summary>
            /// 左缩进
            /// </summary>
            /// <param name="fltCount">float类型的数值</param>
            public void SetLeftIndent( float fltCount )
            {
                oWordApplic.Selection.ParagraphFormat.LeftIndent = fltCount;
            }        /**//// <summary>
            /// 右缩进
            /// </summary>
            /// <param name="fltCount">float类型的数值</param>
            public void SetRightIndent(float fltCount)
            {
                oWordApplic.Selection.ParagraphFormat.RightIndent = fltCount;
            }        /**//// <summary>
            /// 设置字体类型
            /// </summary>
            /// <param name="strType"></param>
            public void SetFont( string strType )
            {
                switch (strType)
                {
                    case "Bold":
                        oWordApplic.Selection.Font.Bold = 1;
                        break;
                    case "Italic":
                        oWordApplic.Selection.Font.Italic = 1;
                        break;
                    case "Underlined":
                        oWordApplic.Selection.Font.Subscript = 0;
                        break;
                }
                
            }
            
            /**//// <summary>
            /// 设置默认字体
            /// </summary>
            public void SetFont( )
            {
                oWordApplic.Selection.Font.Bold            = 0;
                oWordApplic.Selection.Font.Italic        = 0;
                oWordApplic.Selection.Font.Subscript    = 0;
            
            }        /**//// <summary>
            /// 设置字体名称
            /// </summary>
            /// <param name="strType"></param>
            public void SetFontName( string strType )
            {
                oWordApplic.Selection.Font.Name = strType;
                
            }         /**//// <summary>
            /// 设置字体颜色
            /// </summary>
            /// <param name="Color"></param>
            public void SetFontColor( Word.WdColor Color)
            {
                oWordApplic.Selection.Font.Color = Color;
            }        /**//// <summary>
            /// 设置字体大小
            /// </summary>
            /// <param name="nSize"></param>
            public void SetFontSize( int nSize )
            {
                oWordApplic.Selection.Font.Size = nSize;
                
            }         /**//// <summary>
            /// 设置是否有粗体,0->否 ,1->是
            /// </summary>
            /// <param name="intBoldBi"></param>
            public void setBoldBi( int intBoldBi )
            {
                oWordApplic.Selection.Font.BoldBi = intBoldBi;
                //oWordApplic.Selection.Font.Bold = intBoldBi;
            }        public void SetBoldSize( int intBold )
            {
                oWordApplic.Selection.Font.Bold = intBold;
            }        public void SetUnderLine( Word.WdUnderline underLine )
            {
                oWordApplic.Selection.Font.Underline = underLine; 
            }        public void SetUnderLineColor( Word.WdColor Color )
            {
                oWordApplic.Selection.Font.UnderlineColor = Color;
            }
            /**//// <summary>
            /// 定位到书签
            /// </summary>
            /// <param name="strBookMarkName"></param>
            public void GotoBookMark( string strBookMarkName )
            {
                object missing        = System.Reflection.Missing.value;
                object Book        = (int)Word.WdGoToItem.wdGoToBook;
                object NameBookMark = strBookMarkName;
                oWordApplic.Selection.GoTo( ref Book, ref missing, ref missing,ref NameBookMark );
            }
      

  18.   

    /**//// <summary>
            /// 定位到文档开头
            /// </summary>
            public void GoToTheBeginning( )
            {
                object missing    = System.Reflection.Missing.value;
                object unit;
                unit            = Word.WdUnits.wdStory ;
                oWordApplic.Selection.HomeKey ( ref unit, ref missing );
                
            }         /**//// <summary>
            /// 定位到文档结尾
            /// </summary>
            public void GoToTheEnd( )
            {
                object missing    = System.Reflection.Missing.value;
                object unit;
                unit            = Word.WdUnits.wdStory ;
                oWordApplic.Selection.EndKey ( ref unit, ref missing );
            }         /**//// <summary>
            /// 定位到首段
            /// </summary>
            /// <returns></returns>
            public Word.Paragraph  GoToFirstParagraph()
            {
                return this.oWordApplic.Selection.Paragraphs.First;
            }        /**//// <summary>
            /// 定位到尾段
            /// </summary>
            /// <returns></returns>
            public Word.Paragraph GoToEndParagraph()
            {
                return this.oWordApplic.Selection.Paragraphs.Last ;
            }        /**//// <summary>
            /// 向后定位到指定段落
            /// </summary>
            /// <param name="para"></param>
            /// <param name="count"></param>
            public void GoToNextParagraph(ref Word.Paragraph para,ref object count)
            {
                para.Next(ref count) ;
            }        /**//// <summary>
            /// 向前定位到指定段落
            /// </summary>
            /// <param name="para"></param>
            /// <param name="count"></param>
            public void GoToPreviousParagraph( ref Word.Paragraph para, ref object count )
            {
                para.Previous( ref count ) ;
            }        public void GoToTheTable( int ntable )
            {
                object missing    = System.Reflection.Missing.value;
                object what;
                what            = Word.WdUnits.wdTable ;
                object which;
                which            = Word.WdGoToDirection.wdGoToFirst;
                object count;
                count            = 1 ;
                oWordApplic.Selection.GoTo( ref what, ref which, ref count, ref missing );
            }         public void GoToRightCell( )
            {
                object missing    = System.Reflection.Missing.value;
                object direction;
                direction        = Word.WdUnits.wdCell;
                oWordApplic.Selection.MoveRight( ref direction, ref missing, ref missing );
            }         public void GoToLeftCell( )
            {
                object missing    = System.Reflection.Missing.value;
                object direction;
                direction        = Word.WdUnits.wdCell;
                oWordApplic.Selection.MoveLeft( ref direction, ref missing, ref missing );
            }         public void GoToDownCell( )
            {
                object missing = System.Reflection.Missing.value;
                object direction;
                direction = Word.WdUnits.wdLine;
                oWordApplic.Selection.MoveDown( ref direction, ref missing, ref missing );
            }         public void GoToUpCell( )
            {
                object missing    = System.Reflection.Missing.value;
                object direction;
                direction        = Word.WdUnits.wdLine;
                oWordApplic.Selection.MoveUp( ref direction, ref missing, ref missing );
            }         public Boolean ExecuteReplace( Word.Find find )
            {
                return ExecuteReplace( find, Word.WdReplace.wdReplaceAll );
            }
      

  19.   

    public Boolean ExecuteReplace( Word.Find find, Object replaceOption )
            {
                // Simple wrapper around Find.Execute:
                Object findText = Type.Missing;
                Object matchCase = Type.Missing;
                Object matchWholeWord = Type.Missing;
                Object matchWildcards = Type.Missing;
                Object matchSoundsLike = Type.Missing;
                Object matchAllWordForms = Type.Missing;
                Object forward = Type.Missing;
                Object wrap = Type.Missing;
                Object format = Type.Missing;
                Object replaceWith = Type.Missing;
                Object replace = replaceOption;
                Object matchKashida = Type.Missing;
                Object matchDiacritics = Type.Missing;
                Object matchAlefHamza = Type.Missing;
                Object matchControl = Type.Missing;
          
                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 ExecuteFind( Word.Find find )
            {
                return ExecuteFind( find, find.Text, Type.Missing, Type.Missing );
            }
            public Boolean ExecuteFind( Word.Find find, string strFindText )
            {
                return ExecuteFind( find, strFindText, Type.Missing, Type.Missing );
            }        public Boolean ExecuteFind(
                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( Word.Selection Selection, string strFindText ) 
            {
                            
                return this.ExecuteFind( Selection.Find,strFindText,System.Type.Missing,System.Type.Missing );
            }        public Boolean FindInSelection( Word.Selection Selection, string strFindText, Object wrapFind, Object forwardFind ) 
            {
                            
                return this.ExecuteFind( Selection.Find, strFindText, wrapFind, forwardFind );
            }        public Boolean FindInRange( Word.Range range,string strFindText ) 
            {
                Boolean blnReturn  =this.ExecuteFind( range.Find, strFindText, Type.Missing, Type.Missing );
                range.Select();
                return blnReturn;
            }
      
            public void FindInAllDocument( string strFindText ) 
            {
                int intFound        = 0;
                Object start        = 0;
                Object end            = this.oDoc.Characters.Count;
                Word.Range rngDoc    = oDoc.Range( ref start, ref end );
                Word.Find fnd        = rngDoc.Find;
                fnd.ClearFormatting();
                fnd.Forward        = true;
                fnd.Text        = strFindText;
                ExecuteFind( fnd );
                while ( fnd.Found )
                {
                    rngDoc.Font.Color    = Word.WdColor.wdColorRed;
                    rngDoc.Font.Bold    = 600;
                    intFound++;
                    ExecuteFind( fnd );
                }
                MessageBox.Show( String.Format( "lorem found {0} times.", intFound ), "FindInLoopAndFormat" );
            }
            #endregion
        }
    }