2015-10-14 84 views
0

如何捕獲正在使用c#編寫的word文檔中的文本並將其保存到內存中。 對不起,我的英語和謝謝你的答案從當前文檔中捕獲文本

+0

紅色辦公自動化,它可以讓你與微軟Word進行交互 – user469104

+0

請發佈一些你試過的代碼和錯誤。請參閱堆棧溢出的發佈準則。謝謝! – maxshuty

回答

0

首先,你必須添加Microsoft.Office.Interop.Word從這裏的參考。

enter image description here

然後你就可以讀你的Word文檔中的句子串名單是這樣的:

using Word = Microsoft.Office.Interop.Word; 

public List<string> ReadWordDoc() 
{ 
    object objMissing = System.Reflection.Missing.Value;    
    //Start Word application. 
    Word._Application wordApp; 
    Word._Document wordDoc; 
    wordApp = new Word.Application(); 
    wordApp.Visible = false; 

    object fileName = @"c:\temp\TestWord.docx"; 

    wordDoc = wordApp.Documents.Open(ref fileName, 
     ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, 
     ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, 
     ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing); 

    List<string> sentences = new List<string>(); // List to store sentences. 
    Word.Range rng; 
    for (int i = 1; i < wordDoc.Sentences.Count+1; i++) 
    { 
     object startLocation = wordDoc.Sentences[i].Start; 
     object endLocation = wordDoc.Sentences[i].End; 

     // Supply a Start and End value for the Range. 
     rng = wordDoc.Range(ref startLocation, ref endLocation); 

     // Select the Range. 
     rng.Select(); 
     sentences.Add(rng.Text); 
    } 
    object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; 
    wordDoc.Close(ref doNotSaveChanges, ref objMissing, ref objMissing); 
    wordApp.Quit(ref objMissing, ref objMissing, ref objMissing); 

    return sentences; 
} 
+0

謝謝我的朋友,一切都好,但問題是我需要捕捉正在使用的單詞的文本。 我試圖從一個Word插件來做到這一點。非常感謝 – Batista

+0

我解決了這個問題,使用兩種保存方法,而我的用戶在一個寫入另一個讀 – Batista

0

@Batista:如果你問如何監控用戶正在做Word應用程序 - 「捕捉你正在寫的文字」 - 然後簡短的回答是你不能。在Word API中沒有任何內容支持監視擊鍵和鼠標操作,缺少一些事件,如WindowSelectionChange,WindowBeforeDoubleClick和WindowBeforeRightClick。

較長的答案是可以使用Windows API進行一些監視。如果您進行Google搜索,您應該參與一些代碼示例的討論。我見過的是在MSDN的VSTO論壇(https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vsto)。但是,您的里程可能會有所不同,因爲Windows API截取Word應用程序中消息的有效性在Word和Windows版本之間有所不同。