您好!请问最近的版本中有更简便的解决方法吗?
我在word表格的中间某一列定义了一个书签bookMark1,如附件中所示。
在实际应用过程中,我并不知道单元格的具体位置,只能根据书签bookMark1的信息,获取书签定义区域内第一个单元格的内容(即Test1),我尝试了许多方法,都无法正确获取,请问有什么方法可以获取吗?
String input = "data/newTest.docx";
String output = "output/extractBookmarkText.txt";
//Load Document
Document doc = new Document();
doc.loadFromFile(input);
//Creates a BookmarkNavigator instance to access the bookmark
BookmarksNavigator navigator = new BookmarksNavigator(doc);
//Locate a specific bookmark by bookmark name
navigator.moveToBookmark("bookMark1");
TextBodyPart textBodyPart = navigator.getBookmarkContent();
//Iterate through the items in the bookmark content to get the text
for (int i = 0; i < textBodyPart.getBodyItems().getCount(); i++)
{
if (textBodyPart.getBodyItems().get(i) instanceof Paragraph)
{
Paragraph itemPara = (Paragraph)textBodyPart.getBodyItems().get(i);
for (int j = 0; j < itemPara.getChildObjects().getCount(); j++)
{
if (itemPara.getChildObjects().get(j) instanceof TextRange)
{
TextRange textrange = (TextRange)(itemPara.getChildObjects().get(j));
String text = textrange.getText();
//create a new TXT file to save the text
writeStringToTxt(text,output);
}
}
}
}
}
public static void writeStringToTxt(String content, String txtFileName) throws IOException {
FileWriter fWriter= new FileWriter(txtFileName,true);
try {
fWriter.write(content);
}catch(IOException ex){
ex.printStackTrace();
}finally{
try{
fWriter.flush();
fWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}