批注是一種常用於對特定文檔內容進行注解的工具或方法,起到解釋說明、標記指正的作用。在本篇文章中,將介紹如何操作Word批注的方法,包括:
1. 添加批注:添加文本到批注、插入圖片到批注;
2. 回復批注;
3. 修改或替換批注:用文本替換批注中的文本內容、用文本替換批注中的圖片、用圖片替換批注中的圖片;
4. 刪除批注:刪除指定批注中的所有內容、刪除指定批注中的指定內容
使用工具:Free Spire.Doc for Java (免費版)
Jar文件導入(參考):
方法1:通過官網獲取jar包,並解壓。
導入步驟1:在程序中新建一個Directory目錄,並將控件包中lib文件夾下的Spire.Doc.jar文件(如下圖)復制到新建的目錄下。

導入步驟2:鼠標右鍵點擊復制后的jar文件,選擇“Add as Library”,彈出的對話框中,點擊“OK”,完成導入。
方法2:通過添加maven依賴導入到maven項目,參考導入步驟。
Java示例代碼
【示例1】添加批注(文本、圖片)
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.fields.Comment; public class AddComment { public static void main(String[] args) { //加載測試文檔 Document doc = new Document("test.docx"); //獲取指定段落 Section sec = doc.getSections().get(0); Paragraph para= sec.getParagraphs().get(3); //插入文本到批注 Comment comment = para.appendComment("請在試驗中將包含以下特征的實驗樣本記錄在冊,並整理好周記錄報表,供后續觀察取樣。"); comment.getFormat().setAuthor("審校組"); //插入圖片到批注 comment.getBody().addParagraph().appendPicture("tp.png"); //保存文檔 doc.saveToFile("AddComment.docx", FileFormat.Docx_2010); } }
批注添加效果:

【示例2】回復批注
import com.spire.doc.*; import com.spire.doc.fields.Comment; public class ReplyComment { public static void main(String[] args) throws Exception{ //加載測試文檔 Document doc = new Document("AddComment.docx"); //獲取指定批注 Comment comment = doc.getComments().get(0); //回復批注 Comment relyC= new Comment(doc); relyC.getFormat().setAuthor("實驗組"); relyC.getBody().addParagraph().appendText("已完成。"); comment.replyToComment(relyC); //保存文檔 doc.saveToFile("ReplyComment.docx",FileFormat.Docx_2010); } }
批注回復效果:

【示例3】修改或替換批注
import com.spire.doc.*; public class ModifyComment { public static void main(String[] args){ //加載含有批注的測試文檔 Document doc = new Document("sample.docx"); //獲取第一個批注中的第一段,用文本替換原有批注中的文本 doc.getComments().get(0).getBody().getParagraphs().get(0).replace("請在試驗中將包含以下特征的實驗樣本記錄在冊,並整理好周記錄報表,供后續觀察取樣。","參照以下實驗方法!",false,false); //獲取第一個批注中的第二段,用文本替換原有批注中的圖片 doc.getComments().get(0).getBody().getParagraphs().get(1).setText("請上報管理科!"); //獲取第一個批注中的第三段,刪除原有圖片,再調用方法添加新圖片(用圖片替換圖片) doc.getComments().get(0).getBody().getParagraphs().get(2).getChildObjects().removeAt(0); doc.getComments().get(0).getBody().getParagraphs().get(2).appendPicture("2.png"); //保存文檔 doc.saveToFile("ModifyComment.docx",FileFormat.Docx_2010); } }
修改或替換結果:

【示例4】刪除批注
import com.spire.doc.*; import com.spire.doc.FileFormat; public class DeleteComment{ public static void main(String[] args) { //加載測試文檔 Document doc = new Document("AddComment.docx"); //調用方法刪除指定批注(刪除批注中的所有內容) doc.getComments().removeAt(0); //刪除指定批注中的指定段落(刪除批注中的部分內容) doc.getComments().get(0).getBody().getParagraphs().get(1).getChildObjects().removeAt(0); //保存文檔 doc.saveToFile("DeleteComment", FileFormat.Docx_2010); } }
批注刪除效果:

(本文完)
轉載請注明出處!!!!!
