在Java操作Word书签(一)中介绍了给Word中的特定段落或文字添加书签、读取及删除已有书签的方法,本文将继续介绍Java 操作Word书签的方法,即如何给已有的书签添加内容,包括添加文本、图片、表格等。 使用工具:Free Spire.Doc for Java (免费版) Jar文件获取及导入: 方法1: 通过官网下载jar文件包。下载后,解压文件。并将lib文件夹下的Spire.Doc.jar文件导入到java程序。参考如下导入效果: 方法2:可通过maven仓库安装导入。可参考安装导入方法。
Java代码示例 【示例1】添加图片、文本到书签 import com.spire.doc.*; import com.spire.doc.documents.BookmarksNavigator; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextWrappingStyle; import com.spire.doc.fields.DocPicture; public class AddImgToBookmarkcontent { public static void main(String[]args){ //加载包含书签的文档 Document doc = new Document(); doc.loadFromFile("test.docx"); //定位到指定书签位置起始标签位置,插入图片 BookmarksNavigator bookmarksNavigator1 = new BookmarksNavigator(doc); bookmarksNavigator1.moveToBookmark("bookmark1",true,false); Paragraph para = new Paragraph(doc); DocPicture picture = para.appendPicture("eth.png"); picture.setTextWrappingStyle(TextWrappingStyle.Through); bookmarksNavigator1.insertParagraph(para); //定位到指定书签位置末尾标签位置,插入文本 BookmarksNavigator bookmarksNavigator2 = new BookmarksNavigator(doc); bookmarksNavigator2.moveToBookmark("bookmark1",false,true); bookmarksNavigator2.insertText("新插入的文本!!!"); //保存文档 doc.saveToFile("addImgToBookmarkcontent.docx",FileFormat.Docx_2013); doc.dispose(); } } 文本、图片添加效果:
【示例2】添加表格到书签内容 import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.TextRange; public class AddTableToBookmarkcontent { public static void main(String[]args){ //加载包含书签的文档 Document doc = new Document(); doc.loadFromFile("test.docx"); //声明数组内容 String[][] data = { new String[]{"班级", "姓名", "学号"}, new String[]{"1班", "刘楠", "Y12534"}, new String[]{"2班", "刘莉", "Y12547"}, new String[]{"3班", "方红", "Y12365"}, }; //创建表格 Table table = new Table(doc, true); table.resetCells(4, 3); for (int i = 0; i < data.length; i++) { TableRow dataRow = table.getRows().get(i); for (int j = 0; j < data[i].length; j++) { TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); range.getCharacterFormat().setFontName("楷体"); dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); } } //定位到指定书签位置,添加表格 BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(doc); bookmarksNavigator.moveToBookmark("bookmark1"); bookmarksNavigator.insertTable(table); //保存文档 doc.saveToFile("addTableToBookmarkcontent.docx",FileFormat.Docx_2013); doc.dispose(); } } 表格添加效果:
(本文完) 转载请注明出处!
来源:https://www.cnblogs.com/Yesi/p/11422252.html 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |
由美国波士顿设计工作室Bluerock Design为Cycle Kids的Breakaway...详情
移动设备正超过桌面设备,成为访问互联网的最常见终端。于是,网...详情
在之前的原创文章中,我陆陆续续介绍了《PS高手完全自学宝典》、...详情
James Bertrand,2011年创立了巴黎一家设计工作室,主要从事平面...详情
学习UI设计到底需不需要美术功底,因为这个问题很多人都在问,很...详情
人工智能正在离我们越来越近,越来越多的人开始关注这个领域。之...详情