从当前文档中捕获文本

时间:2015-10-14 17:10:55

标签: c# c#-4.0 ms-word c#-3.0

如何使用c#捕获您在word文档中编写的文本并将其保存到内存中。 对不起我的英文,谢谢你的回答

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

@Batista:如果您正在询问如何监控用户在Word应用程序中正在做什么 - &#34;捕获您正在编写的文本&#34; - 那么简短的回答就是你做不到。 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版本而异。

答案 2 :(得分:0)

感谢jhmt,您的解决方案非常有帮助。但是在大型文档中,这两个句子之间的 loop 需要很多时间。

现在是我的解决方法:

var objRange = Globals.ThisAddin.Application.ActiveDocument.Range();

然后带有objRange.Text的文档已包含所有文本。