如何在文本运行中搜索特定文本(在 Docx 中使用 OpenXML SDK 2.0),一旦找到它,如何在“搜索文本”周围插入注释。“搜索文本”可以是现有运行的子字符串。示例中的所有示例都在第一段周围插入注释或类似的简单内容......不是我想要的。
谢谢
您必须将其分解为单独的运行。尝试使用 DocumentReflector(它甚至生成 C# 代码)来查看使用 word 创建的文档。结构应该看起来像这样(简化):
<paragraph>
<run>...</run>
<commentRangeStart />
<run>search text</run>
<commentRangeEnd />
<run>...</run>
</paragraph>
对于可能仍在寻找答案的人:
这是代码:
private void AddComment( Paragraph paragraph, string text )
{
string commentId = GetNextCommentId();
Comment comment = new Comment() { Id= commentId, Date = DateTime.Now };
Paragraph commentPara = new Paragraph( new Run( new Text( GetCommentsString( text ) ) ) { RunProperties = new RunProperties( new RunStyle() { Val = "CommentReference" } ) } );
commentPara.ParagraphProperties = new ParagraphProperties( new ParagraphStyleId() { Val = "CommentText" } );
comment.AppendChild( commentPara );
_comments.AppendChild( comment );//Comments object
_comments.Save();
paragraph.InsertBefore( new CommentRangeStart() { Id = commentId }, paragraph.GetFirstChild<Run>() );
var commentEnd = paragraph.InsertAfter( new CommentRangeEnd() { Id = commentId }, paragraph.Elements<Run>().Last() );
paragraph.InsertAfter( new Run( new CommentReference() { Id = commentId } ), commentEnd );
}