如果已经打开读取的原稿中存在的窗口

问题描述 投票:1回答:1

试图读取word文档和显示文档中用户特定的标题。

如果文件没有打开,它目前将其打开。目前,无论如何,它会在新窗口中打开该文档。

我试图让来读取其在当前打开的窗口。如果文档已经在它打开。

试图寻找在其他论坛/堆栈溢出的答案与微软的文档一起,但我迷路了,找到一个解决方案。

public void DocumentPreview(string headingNumber, string headingName,string inputPath)
{
    var application = new Microsoft.Office.Interop.Word.Application();
    var document = application.Documents.Open(FileName: inputPath);

    foreach (Paragraph paragraph in document.Paragraphs)
    {
        Style style = paragraph.get_Style() as Style;
        string styleName = style.NameLocal;
        string text = paragraph.Range.Text;
        if ((styleName == "Heading 1") || (styleName == "Heading 2") ||
            (styleName == "Heading 3") || (styleName == "Heading 4"))
        {
            List<string> headingSplit = headingName.Split().ToList();
            double count = 0;
            foreach (string word in headingSplit)
            {
                if (text.ToString().ToLower().Contains(word.ToLower()))
                {
                    count += 1;
                }
            }
            double accuracy = (count / headingSplit.Count());
            if (accuracy >= 0.5)
            {
                if (text.ToString().ToLower().Contains(headingNumber.ToLower()))
                {
                    Word.Range rng = paragraph.Range;
                    rng.Select();
                    break;
                }
            }
        }
    }
}

目前打开一个文档在新窗口中每一次,而不是当前窗口,如果,如果已经打开。

c# .net winforms ms-word office-interop
1个回答
0
投票

确保你通过保持它在一个表单域,而不是一个局部变量使用Word应用程序的单一实例。然后检查DocumentsApplication集合包含具有相同Document属性值Path,使用它inputPath

要做到这一点,你可以创建这样的功能:

//using MSWord = Microsoft.Office.Interop.Word;
private MSWord.Document OpenDocument(MSWord.Application application, string inputPath)
{
    var documents = application.Documents;
    foreach (MSWord.Document item in documents)
        if (item.Path.ToUpper() == inputPath.ToUpper())
            return item;
    return documents.Open(FileName: inputPath);
}

作为使用的一个示例:

MSWord.Application application;
private void button1_Click(object sender, EventArgs e)
{
    if (application == null)
    {
        application = new MSWord.Application();
        application.Visible = true;
    }
    var document = OpenDocument(application, @"d:\test.docx");
    // ...
}

确保你Quit应用程序时,你不需要它。

© www.soinside.com 2019 - 2024. All rights reserved.