2

我正在使用运行 .NET 4.0 的 VSTO 2010 开发一个 .NET 程序,以在一组 word 文档中查找特定的子标题,并使用Word.Interop复制该子标题下的所有内容(比如“要求”)。我通过匹配 words 的 for 循环成功了,我使用它搜索这个词,然后搜索下一部分的起始词(比如“功能”)。

现在文档也有一个内容页面,所以我发现简单的单词匹配不会做,因为它会返回第一个出现的事件,这肯定是在内容部分。所以我试着找到第二次出现 an 是成功的,但后来意识到这个词甚至可能在副标题之前重复很多次。因此,我求助于寻找句子。在这里,我在这里成功地找到了这两个词(我不得不将搜索字符串修改为“Requirements\r”,因为这就是它的读取方式)无论如何。我现在面临的问题是,在我得到开头和结尾的句子后,我选择了整个文档并使用 MoveStart 和 MoveEnd ,我在复制它并将其粘贴到另一个 word 文档之前减少了选择,(因为我不知道如何使用 Range 或 Bookmark)但是,虽然我成功地移动了开始并且结束位置是正确的,但MoveEnd 总是移动到一些文本,该文本至少超出实际 10 个句子。我已经在这里工作了 2 周,非常感谢您在这件事上提供的任何帮助。我并不是说对世界上所有的程序员有任何不尊重。我已经展示了我正在使用的代码。

使用的变量是不言自明的。//SourceApp 和 SourceDoc - 读取发行说明源的 Word 应用程序 //DestinationApp 和 DestinationDoc = 写入新文档的 Word 应用程序

    private void btnGenerate_Click(object sender, EventArgs e)
    {
        int startpos = findpos(SourceDoc, 1, starttext, sentencecount);
        int endpos = findpos(SourceDoc, startpos, endtext, sentencecount);

        object realstart = startpos - 1; // To retain the subheading
        object realend = -(sentencecount - (endpos - 1)); // to subtract the next subheading

        SourceDoc.Activate();
        SourceDoc.ActiveWindow.Selection.WholeStory();
        SourceDoc.ActiveWindow.Selection.MoveStart(WdUnits.wdSentence, realstart);
        SourceDoc.ActiveWindow.Selection.MoveEnd(WdUnits.wdSentence, realend); // the problematic bit
        SourceDoc.ActiveWindow.Selection.Copy();
        IDataObject data = Clipboard.GetDataObject();
        string allText = data.GetData(DataFormats.Text).ToString();

        DestinationDoc.Activate();
        DestinationDoc.ActiveWindow.Selection.WholeStory();
        DestinationDoc.ActiveWindow.Selection.Delete();
        DestinationDoc.ActiveWindow.Selection.Paste();
        DestinationDoc.Save();

        ((_Application)SourceApp).Quit();
        ((_Application)DestinationApp).Quit();
        textBox1.AppendText(allText);

    }


    int findpos(Document docx, int startpos, string txt, int sentencecount)
    {
        int pos = 0;
        string text;
        for (int i = startpos; i <= sentencecount; i++)
        {
            text = docx.Sentences[i].Text;
            if (string.Equals(text, txt))
            {
                pos = i;
                break;
            }
        }

        return pos;
    }

如果有一种方法可以仅提取特定的副标题(如 3.1 、 5.2.3 等),我也将非常感激,这正是我想要实现的。问题只是我做事的方式,我也愿意接受更好的方式。提前谢谢了。

4

0 回答 0