本文将介绍通过使用spire.doc for .net给word中的指定字符串添加批注的方法。
c#
using spire.doc;
using spire.doc.documents;
using spire.doc.fields;
using system;
namespace addcommenttocharacters
{
class program
{
static void main(string[] args)
{
//加载测试文档
document doc = new document();
doc.loadfromfile("test.docx");
//查找指定字符串
textselection[] selections = doc.findallstring("考核目的", true, false);
//获取关键字符串所在段落
paragraph para = selections[0].getasonerange().ownerparagraph;
int index = para.childobjects.indexof(selections[0].getasonerange());
//设置批注id
commentmark start = new commentmark(doc);
start.commentid = 1;
start.type = commentmarktype.commentstart;
commentmark end = new commentmark(doc);
end.type = commentmarktype.commentend;
end.commentid = 1;
//添加批注内容
string str = "给指定字符串添加批注";
comment comment = new comment(doc);
comment.format.commentid = 1;
comment.body.addparagraph().appendtext(str);;
comment.format.author = "作者:";
comment.format.initial = "cm";
para.childobjects.insert(index, start);
para.childobjects.insert(index 1, selections[0].getasonerange());
para.childobjects.insert(index 2, end);
para.childobjects.insert(index 3, comment);
//保存文档
doc.savetofile("字符串批注.docx", fileformat.docx2013);
}
}
}
vb.net
imports spire.doc
imports spire.doc.documents
imports spire.doc.fields
imports system
namespace addcommenttocharacters
class program
private shared sub main(byval args() as string)
'加载测试文档
dim doc as document = new document
doc.loadfromfile("test.docx")
'查找指定字符串
dim selections() as textselection = doc.findallstring("考核目的", true, false)
'获取关键字符串所在段落
dim para as paragraph = selections(0).getasonerange.ownerparagraph
dim index as integer = para.childobjects.indexof(selections(0).getasonerange)
'设置批注id
dim start as commentmark = new commentmark(doc)
start.commentid = 1
start.type = commentmarktype.commentstart
dim end as commentmark = new commentmark(doc)
end.type = commentmarktype.commentend
end.commentid = 1
'添加批注内容
dim str as string = "给指定字符串添加批注"
dim comment as comment = new comment(doc)
comment.format.commentid = 1
comment.body.addparagraph.appendtext(str)
comment.format.author = "作者"
comment.format.initial = "cm"
para.childobjects.insert(index, start)
para.childobjects.insert((index 1), selections(0).getasonerange)
para.childobjects.insert((index 2), end)
para.childobjects.insert((index 3), comment)
'保存文档
doc.savetofile("字符串批注.docx", fileformat.docx2013)
end sub
end class
end namespace
字符串批注添加效果: