本文將介紹在Java程序中如何給Word文檔中的指定字符串添加批註。前文中,主要介紹的是針對某個段落來添加批註,以及回覆、編輯、刪除批註的方法,若是須要針對特定關鍵詞或指定字符串來設置批註,能夠參考本文的方法。html
使用工具:Free Spire.Doc for Java (免費版)java
獲取方法1:經過官網下載,並導入Spire.Doc.jar文件至java程序。app
獲取方法2:經過maven倉庫安裝導入。可參考方法教程。maven
Java代碼示例工具
import com.spire.doc.*; import com.spire.doc.documents.CommentMark; import com.spire.doc.documents.CommentMarkType; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextSelection; import com.spire.doc.fields.Comment; public class AddCommentToCharacters { public static void main(String[] args) { //加載測試文檔 Document doc = new Document(); doc.loadFromFile("test.docx"); //查找指定字符串 TextSelection[] selections = doc.findAllString("皺狀厚膜", true, false); //獲取關鍵字符串所在段落 Paragraph para = selections[0].getAsOneRange().getOwnerParagraph(); int index = para.getChildObjects().indexOf(selections[0].getAsOneRange()); //添加批註ID CommentMark start = new CommentMark(doc); start.setCommentId(1); start.setType(CommentMarkType.Comment_Start); CommentMark end = new CommentMark(doc); end.setType(CommentMarkType.Comment_End); end.setCommentId(1); //添加批註內容 String str = "給指定字符串添加批註"; Comment comment = new Comment(doc); comment.getFormat().setCommentId(1); comment.getBody().addParagraph().appendText(str); comment.getFormat().setAuthor("做者:"); comment.getFormat().setInitial("CM"); para.getChildObjects().insert(index, start); para.getChildObjects().insert(index + 1, selections[0].getAsOneRange()); para.getChildObjects().insert(index + 2,end); para.getChildObjects().insert(index + 3, comment); //保存文檔 doc.saveToFile("字符串批註.docx",FileFormat.Docx_2013); doc.dispose(); } }
批註添加效果:測試
(本文完)spa