C#操作Word

c#操作word表格 最近由于工作需要,做了一些关于c#操作word文档方面的工作.主要是对word中表格的操作,以下是部分代码,关于操作不规则表格的.using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System. 阅读详情
C#操作Word!
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();
                }

            }

        }


        
/// <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 } );
                    
其它格式:
                    result 
= true;
                }

                
catch
                
{
                    
//throw ( new Exception() );
                }

                
finally
                
{
                    
this.Quit();
                }

            }

            
return result;
        }


        
/// <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();
        }


        
/// <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 Bookmark        = (int)Word.WdGoToItem.wdGoToBookmark;
            
object NameBookMark = strBookMarkName;
            oWordApplic.Selection.GoTo( 
ref Bookmark, ref missing, ref missing,ref NameBookMark );
        }


        
/// <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 );
        }


        
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

    }

}

posted @ 2007-08-17 15:30 暮江独钓 阅读(150) 评论(1)   编辑 收藏 网摘 所属分类: .net

td { font-size: 12px } .commentTextBox { font-family : Verdana; font-size: 13px; } a.blue:visited, a.blue:active, a.blue:link, a.blue:hover { color:blue; } .userData { BEHAVIOR: url(#default#userdata) }
c# Word操作 Spire.XLS是E-iceblue开发的一套基于企业级的专业Office文档处理的组件之一,全称Spire.Office for .NET。旗下有Spire.Doc,Spire XLS,Spire.PDF,Spire.BarCode等多款专业组件,为各种Office文档在程序处理上提供了很大的方便,官方为各种功能提供了大量的在线api,简化了使用组件的难度。组件使用时不需要本地Office组件的支持。 阅读详情

相关推荐

C#中操作Word组件的完全指南

在C#开发中,利用组件对象模型(Component Object Model, COM)组件可以扩展应用程序的功能。通过封装遗留代码或利用现成的第三方库,开发人员可以将这些COM组件集成到C#应用程序中,以实现丰富的交互功能。

weixin_32099703的博客 1049

C# Word操作

1、Word文件插入图表(通过Excel生成图表,再粘贴至Word文件)。2、Word文件插入表格。

zhujing0613的博客 940

C#操作word文档(多种方法)

平时学习时注意做笔记,赫赫,上传上来跟大家分享!内容概要:1、运用 Range 对象处理 Word 文档内容;2、如何使用C#在Word文档中插入图片以及读取Word文档中的图片?3、提取word 文档中的图片信息;4、提取WORD中的所有InlineShape图片并保存成文件;5、C#编程实现动态生成Word文档{1、2};6、C#读取Word文档的详细例子

C#操作Word的超详细总结

本文中用C#来操作Word,包括: 创建Word; 插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等; 设置段落的首行缩进、行距; 设置页面页边距和纸张大小; 设置页眉、页码; 插入图片,设置图片宽高以及给图片添加标题; 插入表格,格式化表格,往表格中插入数据; 保存Word,打印Word; 重新打开Word等。 Visual studio版本:Visual...

ZeroCode 8234

大红球预警版-精选+自定义板块监控

这是一款简单易用的股票大单资金监控插件,兼容通达信软件,可嵌入分时图或定制版面。它以红绿圆球直观显示主力买卖情况(红球为买,绿球为卖),支持300万以上大单语音播报。插件提供实时资金流向分析、多股同时监控、自定义预警条件等功能,无需L2账号。用户可自由切换图形/列表模式,监控特定板块,并配合幻影软件实现自动交易。虽然上涨股通常红球占优,但需结合其他指标综合判断。该插件完全免费,包含详细视频教程,适合新手使用。

guleba的博客 1794

OpenCV学习笔记(25)基于MFC和OpenCV的摄像机定标与立体匹配测试程序(20140505更新)

最近整理了一下这两年一直在用的摄像机定标与立体匹配测试程序,将代码进行了重构,界面也做了调整,分享出来方便有需要的朋友使用。当然我的编程能力有限,程序可能还有各种bug,请大家多多包涵。相关问题欢迎留言或email联系讨论,谢谢! ==================================================================================源码

晨宇思远 5万+

使用C#中的Aspose Word 在对Word文档中的书签详细总结(包括增删改查等操作)

在Word文档中,书签是用于标记文档中某个位置的一种标识符。它是一个有名字的位置,可以用于跳转、插入文本、插入图片等操作。当需要在文档中插入一些内容时,可以先在需要插入内容的位置插入一个书签,然后通过书签的名称来定位这个位置,并在这个位置插入内容。

QHCV的博客 3991

C语言实现俄罗斯方块

使用C语言完成俄罗斯方块。《俄罗斯方块》的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分。由小方块组成的不同形状的板块陆续从屏幕上方落下来,玩家通过调整板块的位置和方向,使它们在屏幕底部拼出完整的一条或几条。这些完整的横条会随即消失,给新落下来的板块腾出空间,与此同时,玩家得到分数奖励。没有被消除掉的方块不断堆积起来,一旦堆到屏幕顶端,玩家便告输,游戏结束。顾名思义,俄罗斯方块自然是俄罗斯人发明的。

qq_54169998的博客 7万+

C# 操作Word

C#操作Word

c_c33的博客 5192

读书笔记:深度学习入门-基于python的理论与实现(俗称鱼书)

终于从头到尾把鱼书看完啦,真的是非常入门,非常查漏补缺,对新手很友好,对有一定基础的人也非常不错。看完不复习等于没看,所以今天开始复盘,顺便写这篇读书笔记。希望分享给没看过这本书或者看过这本书的同僚们参考,欢迎大家指教。我将从第三章神经网络开始复习,前两章内容书里已经非常基础and清楚了。(会持续更新滴).........

博客而已 1万+

Fiori Elements 从入门到精通开发教程的文章目录

Fiori Elements 开发技术相对 SAP 其他历史悠久,发展成熟的开发技术来说,是一个新事物。正因如此,迄今为止国内深入讲解 Fiori Elements 应用的中文材料几乎没有。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 4775

用 c# 来操作WORD的经验总结

用 c# 来操作WORD的经验总结

weixin_43931979的博客 2790

【腾讯小龙虾 WorkBuddy 专栏 03】技能(Skills)制作全教程!自定义技能编写、导出分享、导入使用一步到位

🔥腾讯AI智能体WorkBuddy自定义技能全攻略 本文为零基础用户提供WorkBuddy自定义技能的完整教程,涵盖技能概念、编写规范到实操全流程。核心内容包括: 技能本质:标准化任务指令模板,可固化重复操作流程 三大价值:一键执行重复任务/跨设备共享/降低使用门槛 实操演示:以"桌面文档自动分类"为例,分步讲解编写、测试、导出 共享方案:支持单技能/批量导出,通过任意渠道传输分享 导入指南:3秒完成他人技能加载,并提供常见问题解决方案 高阶优化:增加异常处理、版本管理等提升技能普适性

AI人人懂 2966

C#操作word文档

1.c#操作word 在指定书签插入文字或者图片using Word = Microsoft.Office.Interop.Word;object Nothing = System.Reflection.Missing.Value;         object format = Word.WdSaveFormat.wdFormatDocument;         Word.Applic

liusen5555的专栏 1万+

由Sensor光谱响应曲线联想到的白平衡增益计算

由Sensor光谱响应曲线联想到的白平衡增益计算 由于传感器硬件的限制,传感器在某个预定波长范围内的响应不可能是100% 响应。现实中都是类似于正态分布的单峰函数。如果仅做粗略计算,由一个中心波长和半高宽(也成半波宽)完全可以由数学公式计算出一个高斯分布曲线。这个分布曲线就叫波谱响应函数。 波谱响应函数反映了传感器通道获取能量的情况。实际上每个传感器厂商都提供了具体的光谱响应函数,一般由两列数据组成,一列数据是波长,另一列数据是相对响应强度。下图某sensor光谱的响应的波谱响应函数。 ...

大熊 7490

Linkage Mapper 输出文件夹结构解析——LCPs(栅格廊道)、LinkagePaths(矢量廊道)、Nodes(节点)

Linkage Mapper输出文件解析摘要 Linkage Mapper是生态连通性分析的重要工具,通过最小累积阻力模型(MCR)识别物种迁移廊道。其输出包含三类核心文件: LCPs(栅格廊道):存储累积阻力值的栅格数据,直观展示低阻力路径,适用于空间分析和廊道质量评估。 LinkagePaths(矢量廊道):以矢量线状要素精确记录廊道位置和走向,便于地图可视化及连通性分析。 Nodes(节点):标记廊道关键点(起点/终点/交汇点),为保护策略制定提供依据。 典型应用场景包括: 山地物种(如大熊猫)栖息地

走向CTO的路上... 1332

C#操作Word方法详细大汇总

本文中用C#来操作Word,包括: 创建Word; 插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等; 设置段落的首行缩进、行距; 设置页面页边距和纸张大小; 设置页眉、页码; 插入图片,设置图片宽高以及给图片添加标题; 插入表格,格式化表格,往表格中插入数据; 保存Word,打印Word; 重新打开Word等。 Visual studio版本:Visual Studio 2012(201...

T643685558的博客 5761

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

[转]C#操作Word的超详细总结

C# Word .NET

m0_67187094的博客 5534

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

c#操作word

 C#代码 using System;   using System.ComponentModel;   using System.Data;   using System.Windows.Forms;     using Word = Microsoft.Office.Interop.Word;     namespace ImportExport

szg3827的专栏 834

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

C# 操作word文档

object oFileName = @"C:/Documents and Settings/liush/My Documents/TestDoc.doc";object oReadOnly = true;object oMissing = System.Reflection.Missing.Value;Word._Application oWord;Word._Document oDoc;o

okin 1847

【转载】C#操作Word的超详细总结

C#操作Word的超详细总结 本文中用C#来操作Word,包括: 创建Word; 插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等; 设置段落的首行缩进、行距; 设置页面页边距和纸张大小; 设置页眉、页码; 插入图片,设置图片宽高以及给图片添加标题; 插入表格,格式化表格,往表格中插入数据; 保存Word,打印Word; 重新打开Word等。 Visual studio版本:Visual Studio 2012(2010应该也可以) 准备工作: /* 1...

yunxiaobaobei的博客 2307

C#操作office方面的总结 Excel和Word

C#操作office方面的总结 Excel和Word C#操作Excel!    public class ImportExportToExcel    {        private string strConn ;                private System.Windows.Forms.OpenFileDialog openFileDlg=new System.W

MaoMao_1983的专栏 1357

c# 操作Word总结

  在医疗管理系统中为保存患者的体检和治疗记录,方便以后的医生或其他人查看。当把数据保存到数据库中,需要新建很多的字段,而且操作很繁琐,于是想到网页的信息创建到一个word文本中,在显示的时,可以在

wcqlwyt的博客 657
上一篇: C#中正则表达式的总结
下一篇: 编写word木马的shellcode
大浪淘沙1
博客等级 码龄19年 42粉丝 38原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值