在XWPF word文档中存在很多用于读取和编辑/替换书签的示例。 但我想创建一个文档并创建新的书签。 创建文档 - 没问题:
private void createWordDoc() throws IOException {
XWPFDocument document = new XWPFDocument();
File tempDocFile = new File(pathName+"\\temp.docx");
FileOutputStream out = new FileOutputStream(tempDocFile);
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("testing string ");
document.write(out);
out.close();
}
如何在文本“测试字符串”上创建书签?
答案 0 :(得分:3)
直到现在,才在apache poi
的高级别类中实现此功能。因此,需要低级别CTP和CTBookmark。
示例:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import java.math.BigInteger;
public class CreateWordBookmark {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
//bookmark before the run
CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
bookmark.setName("before_testing_string");
bookmark.setId(BigInteger.valueOf(0));
paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(0));
//bookmark the run
bookmark = paragraph.getCTP().addNewBookmarkStart();
bookmark.setName("testing_string");
bookmark.setId(BigInteger.valueOf(1));
XWPFRun run = paragraph.createRun();
run.setText("testing string ");
paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(1));
//bookmark after the run
bookmark = paragraph.getCTP().addNewBookmarkStart();
bookmark.setName("after_testing_string");
bookmark.setId(BigInteger.valueOf(2));
paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(2));
document.write(new FileOutputStream("CreateWordBookmark.docx"));
document.close();
}
}