本文将介绍如何使用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);
}
}