在现有窗口中阅读文档(如果已打开)

时间:2019-02-07 09:07:39

标签: c# .net winforms ms-word office-interop

尝试阅读word文档并在文档中显示用户特定的标题。

如果未打开文档,则当前将其打开。目前,无论如何,它将在新窗口中打开文档。

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

试图在其他论坛/堆栈溢出以及Microsoft文档中寻找答案,但我却找不到解决方案。

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;
                }
            }
        }
    }
}

当前(如果已打开)每次都在新窗口中而不是在当前窗口中打开文档。

1 个答案:

答案 0 :(得分:0)

通过将单词应用程序的单个实例保留在表单字段而不是局部变量中,确保使用它。然后检查Documents的{​​{1}}集合是否包含一个Application属性值与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"); // ... } 应用程序。