2010-02-17 36 views
0

我想創建一個doc文件,並使用文字互操作的一些內容複製到另一個doc文件和C#.eg如何使用Word互操作,並得到一個doc文件特定文本的範圍C#

這是我的doc文件。我只會將這部分粘貼到另一個doc文件。 其餘的文本將只保留在這裏。

我只想粘貼文本「我將粘貼到另一個文件file.Rest」到另一個DOc文件。 任何人都可以幫助我從文檔 得到這一行的範圍我正在使用Interop,但希望從文檔文件中獲取範圍高達特定的詞,並選擇文本到該範圍將其複製到另一個doc文件..我想了解獲取範圍的方法

回答

0

如果文檔可以是DOCX,那麼可以使用非常簡單的DOCX包裝。合併文檔,更改文本部分,查找和替換一些文字非常簡單。作者已經就如何在他的Blog site上使用它做了很多很好的教程。

如果您想要DOC,那麼您必須使用Interop。

例如,如果你想找到一些字並用另一個替換它,你會做它喜歡在博客上建議:

這DOCX的版本允許你搜索一個文件的字符串。函數 FindAll(string str)返回一個列表,其中包含找到的字符串的所有開始索引。 下面是這個新功能的一個例子。

// Load a document 
using (DocX document = DocX.Load(@"Test.docx")) 
{ 
    // Loop through the paragraphs in this document. 
    foreach (Paragraph p in document.Paragraphs) 
    { 
    // Find all instances of 'go' in this paragraph. 
    List<int> gos = document.FindAll("go"); 

    /* 
    * Insert 'don't' in front of every instance of 'go' in this document to produce   * 'don't go'. An important trick here is to do the inserting in reverse document   * order. If you inserted in document order, every insert would shift the index   * of the remaining matches. 
    */ 
    gos.Reverse(); 
    foreach (int index in gos) 
    { 
    p.InsertText(index, "don't ", true); 
    } 
    } 

    // Save all changes made to this document. 
    document.Save(); 
}// Release this document from memory. 

對於DOC和搜索特定字符串,也許你可以整個文檔複製到剪貼板,並找到你所需要的,剪出來:

Word.ApplicationClass wordApp=new ApplicationClass(); 
object file=path; 
object nullobj=System.Reflection.Missing.Value; 
Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj, 
            ref nullobj, ref nullobj, ref nullobj, 
            ref nullobj, ref nullobj, ref nullobj, 
            ref nullobj, ref nullobj, ref nullobj); 
doc.ActiveWindow.Selection.WholeStory(); 
doc.ActiveWindow.Selection.Copy(); 
IDataObject data=Clipboard.GetDataObject(); 
txtFileContent.Text=data.GetData(DataFormats.Text).ToString(); 
doc.Close(); 

記住釋放資源,或者你最終會有很多word.exe進程打開。

這也是一個很好的reading它可以幫助你。

夫婦的文章,你可能會想閱讀:

How to: Search for Text in Documents

How to: Search for and Replace Text in Documents

+1

我使用的互操作,但想從doc文件,比選擇文本高達該範圍內獲得高達特定詞的範圍將它複製到另一個doc文件..我想知道獲取範圍的方法 – aaa 2010-02-17 08:39:09

相關問題