poi 读取word标题_POI读取word文档

最近做了一个word文档导入的功能,但是因为项目紧急,所以做的很粗糙。好不容易周末了,就自己撸了一会代码,想把他做成一个通用的工具,以备以后用到时直接黏贴。

概述

POI 的起源

POI是apache的一个开源项目,他的起始初衷是处理基于Office Open XML标准(OOXML)和Microsoft OLE 2复合文档格式(OLE2)的各种文件格式的文档,而且对于读和写都有支持。可以说是JAVA处理OFFICE文档的首选工具了。

HWPF和XWPF

POI操作word文档的两个主要模块就是HWPF和XWPF。

HWPF是操作Microsoft Word 97(-2007)文件的标准API入口。它还支持对旧版Word 6和Word 95文件对有限的只读功能。

XWPF是操作Microsoft Word 2007文件的标准API入口。

读取word文档

其实,POI对于word文档的读写操作提供了许多API可用,这里只提供最简单的按段落读取文字内容的demo,对于图片读取或表格的读取,以后再更新。

maven依赖

com.google.guava

guava

24.0-jre

org.apache.poi

poi-scratchpad

3.17

org.apache.poi

poi-ooxml

3.17

public static List readWordFile(String path) {

List contextList = Lists.newArrayList();

InputStream stream = null;

try {

stream = new FileInputStream(new File(path));

if (path.endsWith(".doc")) {

HWPFDocument document = new HWPFDocument(stream);

WordExtractor extractor = new WordExtractor(document);

String[] contextArray = extractor.getParagraphText();

Arrays.asList(contextArray).forEach(context -> contextList.add(CharMatcher.whitespace().removeFrom(context)));

extractor.close();

document.close();

} else if (path.endsWith(".docx")) {

XWPFDocument document = new XWPFDocument(stream).getXWPFDocument();

List paragraphList = document.getParagraphs();

paragraphList.forEach(paragraph -> contextList.add(CharMatcher.whitespace().removeFrom(paragraph.getParagraphText())));

document.close();

} else {

LOGGER.debug("此文件{}不是word文件", path);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (null != stream) try {

stream.close();

} catch (IOException e) {

e.printStackTrace();

LOGGER.debug("读取word文件失败");

}

}

return contextList;

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部