0

我有一个代码,我正在使用主互操作程序集遍历 word 文档中存在的每个段落。我本质上所做的是将每个段落中的所有文本提取到一个字符串中。然后我在该字符串中搜索特定的关键词/短语。如果它存在,它将与其他东西交换。然后将段落插入回文档中。

这很完美,但是在某些文档上,正在发生的事情是在段落之间添加了一个新行。经过进一步调查,事实证明段落格式正在改变,即行距从零增加到 12 并且其他事情也发生了变化,包括从段落中删除左缩进等。

我想知道在插入文本时是否有任何方法可以在不更改段落属性的情况下执行上述任务。我的代码包含在下面,以显示我如何遍历文档。

在进入主代码之前,我确实使用以下命名空间打开了一个 word 应用程序和文档:

using Word = Microsoft.Office.Interop.Word

然后是下面的代码

Word.Application app = new Word.Application();
Word.Document doc = app.Documents.Open(filePath, ReadOnly: false);

打开文档后,我做了以下事情:

try
        {
            int totalParagraphs = document.Paragraphs.Count;
            string final;
            for (int i = 1; i <= totalParagraphs; i++)
            {
                string temp = document.Paragraphs[i].Range.Text;
                if (temp.Length > 1)
                {
                    Regex regex = new Regex(findText);
                    final = regex.Replace(temp, replaceText);
                    if (final != temp)
                    {
                        document.Paragraphs[i].Range.Text = final;

                    }
                }
            }
        } catch (Exception) { }

需要注意的是,我有一个带有“temp.Length > 1”的 if 语句。我注意到除了一个空行之外什么都没有,它仍然算作一个段落,并且该段落内的文本长度为 1。当使用空行时,即使没有进行任何替换,当将其重新插入时,它实际上也会再次添加一个额外的行。所以为了解决这个问题,我只是用它来确保段落中至少有一个字母,而不仅仅是一个空行。这样就不会在段落之间添加额外的空行。

4

1 回答 1

1

我已经找到了我自己的问题的答案。我在下面包含了解决方案,以防其他人遇到同样的问题或希望它作为参考。

您需要做的是在进行任何更改之前获取提取文本的段落格式属性。然后,一旦将段落重新插入,将我们之前提取的相同属性设置为插入的段落,以应对可能已经做出的任何更改。完整代码如下:

try
        {
            int totalParagraphs = document.Paragraphs.Count;
            string final;
            for (int i = 1; i <= totalParagraphs; i++)
            {
                string temp = document.Paragraphs[i].Range.Text;

                float x1 = document.Paragraphs[i].Format.LeftIndent;
                float x2 = document.Paragraphs[i].Format.RightIndent;
                float x3 = document.Paragraphs[i].Format.SpaceBefore;
                float x4 = document.Paragraphs[i].Format.SpaceAfter;

                if (temp.Length > 1)
                {
                    Regex regex = new Regex(findText);
                    final = regex.Replace(temp, replaceText);
                    if (final != temp)
                    {
                        document.Paragraphs[i].Range.Text = final;
                        document.Paragraphs[i].Format.LeftIndent = x1;
                        document.Paragraphs[i].Format.RightIndent = x2;
                        document.Paragraphs[i].Format.SpaceBefore = x3;
                        document.Paragraphs[i].Format.SpaceAfter = x4;
                    }
                }
            }
        } catch (Exception) { }
于 2017-07-11T19:12:32.860 回答