5年后,答案是:
注意:此代码仅适用于旧词“doc”文件(不是 docx),Apache POI 也可以处理 docx,但您必须使用另一个 API。
使用Apache POI,maven 依赖项:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
这是代码:
...
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public static void main(final String[] args) throws FileNotFoundException, IOException, NoPropertySetStreamException,
MarkUnsupportedException, UnexpectedPropertySetTypeException {
try (final FileInputStream fs = new FileInputStream("src/test/word_template.doc");
final POIFSFileSystem poifs = new POIFSFileSystem(fs)) {
final DirectoryEntry dir = poifs.getRoot();
final DocumentEntry siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
try (final DocumentInputStream dis = new DocumentInputStream(siEntry)) {
final PropertySet ps = new PropertySet(dis);
final SummaryInformation si = new SummaryInformation(ps);
// Read word doc (not docx) metadata.
System.out.println(si.getLastAuthor());
System.out.println(si.getAuthor());
System.out.println(si.getKeywords());
System.out.println(si.getSubject());
// ...
}
}
}
要阅读文本内容,您将需要额外的依赖项:
<dependency>
<!-- Required for HWPFDocument -->
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
代码:
try (final HWPFDocument doc = new HWPFDocument(fs)) {
return doc.getText().toString();
}