我正在尝试创建一个java应用程序,它将搜索所选doc,docx文件中的特定单词并生成一个报告.该报告将包含搜索单词的页码和行号.现在我所取得的成就是我能够逐段阅读doc和docx文件.但我没有找到任何方法来搜索特定的单词并获得该行和&该单词出现的页码.我搜索了很多,但直到现在都没有运气.希望有人知道这样做的方法.
这是我的代码
if(fc.getSelectedFile().getAbsolutePath().contains("docx")) {
File file = fc.getSelectedFile();
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
XWPFDocument document = new XWPFDocument(fis);
List paragraphs = document.getParagraphs();
System.out.println("Total no of paragraph "+paragraphs.size());
for (XWPFParagraph para : paragraphs) {
System.out.println(para.getText());
}
fis.close();
} else {
WordExtractor extractor = null;
FileInputStream fis = new FileInputStream(fc.getSelectedFile());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++) {
if (fileData[i] != null)
System.out.println(fileData[i]);
}
extractor.close();
}
我正在使用swing,apache poi 3.10.1.
解决方法:
恐怕没有简单的方法可以做到这一点.不存储行和页码,而是根据指定的页面大小,根据文本布局快速计算.该页面定义了文本中的包装位置.
您可以尝试使用适当的EditorKit在JEditorPane中加载文档来实现该功能(例如,参见DocxEditorKit实现的尝试http://java-sl.com/docx_editor_kit.html它提供了基本功能,您可以尝试在此处根据源代码和想法实现您自己的EditorKit).
标签:java,swing,apache-poi
来源: https://codeday.me/bug/20190609/1207185.html