我通过用我的值替换模板文档中的一些占位符文本来生成一个 Word 文档。为此,我使用的是 GemBox.Document,更具体地说,是Find and Replace示例中的这段代码:
var document = DocumentModel.Load("input.docx");
var firstPlaceholder = document.Content.Find("%Text1%").First();
firstPlaceholder.LoadText("Value 1");
var secondPlaceholder = document.Content.Find("%Text2%").First();
firstPlaceholder.LoadText("Value 2");
document.Save("output.docx");
这很好用。
但是现在我有一个场景,其中将替换占位符的值取决于它们的位置,更具体地说,占位符是出现在文档中某个特定段落之前还是之后。
我确实尝试过使用这样的东西:
Paragraph separator = ...
string firstPlaceholderText = "%Text1%";
string separatorText = seperator.Content.ToString();
string wholeDocumentText = document.Content.ToString();
if (wholeDocumentText.IndexOf(firstPlaceholderText) < wholeDocumentText.IndexOf(separatorText))
{
// The placeholder is before the separator...
}
else
{
// The placeholder is after the separator...
}
但是,相同separatorText
的值可能出现在文档中的多个位置,因此string.IndexOf()
对我来说不是一个可行的解决方案。
有没有另一种方法可以进行这种比较,或者另一种方法可以确定某个占位符与其他文档元素相比的位置?