Java 添加文本、图片、表格到Word书签
以下经验内容将分享通过java添加文本、图片、表格到Word已有书签中的方法。
工具/原料
Free Spire.Doc for Java (免费版)
IntelliJ IDEA
Jar文件获取及导入:
1、方法1: 通过官网下载jar文件包。下载后,解压文件。并将lib文件夹下的Spire.Doc.jar文件导入到java程序。参考如下导入效果:

【示例2】添加表格到书签内容
1、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(); } }
2、表格添加效果:
