本文将介绍如何使用Spire.Doc for Java替换Word书签的内容。
使用文本替换书签内容
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class ReplaceBookmark {
public static void main(String[] args){
//加载Word文档
Document doc = new Document("Bookmark.docx");
//定位到书签"SimpleBookmark"
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.moveToBookmark("SimpleBookmark");
//使用文本替换原书签的内容, false表示不保留原来的格式
bookmarkNavigator.replaceBookmarkContent("This is new content", false);
//保存文档
doc.saveToFile("ReplaceWithText.docx", FileFormat.Docx);
}
}
使用Html string替换书签内容
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ParagraphBase;
public class ReplaceBookmark {
public static void main(String[] args){
//加载Word文档
Document doc = new Document("Bookmark.docx");
//临时添加一个section
Section tempSection = doc.addSection();
//添加段落到section并添加Html string到段落
String html = "This Bookmark has been edited
";
tempSection.addParagraph().appendHTML(html);
//获取段落的第一项和最后一项
ParagraphBase firstItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getFirstItem();
ParagraphBase lastItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getLastItem();
//创建TextBodySelection对象
TextBodySelection selection = new TextBodySelection(firstItem, lastItem);
//创建TextBodyPart对象
TextBodyPart bodyPart = new TextBodyPart(selection);
//定位到书签"SimpleBookmark"
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.moveToBookmark("SimpleBookmark");
//使用Html string替换原书签的内容
bookmarkNavigator.replaceBookmarkContent(bodyPart);
//移除临时添加的section
doc.getSections().remove(tempSection);
//保存结果文档
doc.saveToFile("ReplaceWithHTMLString.docx", FileFormat.Docx);
}
}
使用表格替换书签内容
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class ReplaceBookmark {
public static void main(String[] args){
//加载Word文档
Document doc = new Document("Bookmark.docx");
String[][] data =
{
new String[]{"Name", "Capital", "Continent", "Area"},
new String[]{"Bolivia", "La Paz", "South America", "1098575"},
new String[]{"Brazil", "Brasilia", "South America", "8511196"},
new String[]{"Canada", "Ottawa", "North America", "9976147"},
new String[]{"Chile", "Santiago", "South America", "756943"},
};
//创建表格
Table table = new Table(doc, true);
table.resetCells(5, 4);
for (int i = 0; i < data.length; i++) {
TableRow dataRow = table.getRows().get(i);
for (int j = 0; j < data[i].length; j++) {
dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
}
}
//创建TextBodyPart对象
TextBodyPart bodyPart= new TextBodyPart(doc);
bodyPart.getBodyItems().add(table);
//定位到书签"SimpleBookmark"
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
bookmarkNavigator.moveToBookmark("SimpleBookmark");
//使用表格替换原书签的内容
bookmarkNavigator.replaceBookmarkContent(bodyPart);
//保存文档
doc.saveToFile("ReplaceWithTable.docx", FileFormat.Docx);
}
}