在Java中解析Word文档,开发者常用Apache POI、Apache Tika等成熟库实现,以下为详细方法及代码示例:
主流方法及代码实现
Apache POI(推荐)
-
适用格式:
.doc
(HWPF) 和.docx
(XWPF) -
Maven依赖:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version> <!-- .doc支持 --> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> <!-- .docx支持 --> </dependency>
-
解析.docx文件:
import org.apache.poi.xwpf.usermodel.*; import java.io.FileInputStream; public class DocxParser { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("document.docx"); XWPFDocument doc = new XWPFDocument(fis)) { // 1. 提取文本 StringBuilder text = new StringBuilder(); for (XWPFParagraph p : doc.getParagraphs()) { text.append(p.getText()).append("n"); } System.out.println("文本内容: " + text); // 2. 提取表格 for (XWPFTable table : doc.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { System.out.print(cell.getText() + "t"); } System.out.println(); } } // 3. 提取图片(需保存到本地) for (XWPFPictureData pic : doc.getAllPictures()) { byte[] data = pic.getData(); String fileName = pic.getFileName(); // 保存图片到文件系统... } } } }
-
解析.doc文件(旧格式):
import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.extractor.WordExtractor; public class DocParser { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("document.doc"); HWPFDocument doc = new HWPFDocument(fis)) { WordExtractor extractor = new WordExtractor(doc); String text = extractor.getText(); // 获取全文 System.out.println(text); } } }
Apache Tika(自动识别格式)
-
优势:自动检测文件类型,支持Word/PDF/Excel等
-
Maven依赖:
<dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>2.7.0</version> </dependency>
-
代码示例:
import org.apache.tika.Tika; import org.apache.tika.metadata.Metadata; import java.io.FileInputStream; public class TikaParser { public static void main(String[] args) throws Exception { Tika tika = new Tika(); try (FileInputStream fis = new FileInputStream("document.docx")) { Metadata metadata = new Metadata(); String content = tika.parseToString(fis, metadata); System.out.println("内容: " + content); System.out.println("类型: " + metadata.get(Metadata.CONTENT_TYPE)); } } }
关键注意事项
-
格式兼容性:
.docx
(POI的XWPFDocument
)解析更稳定,.doc
(HWPFDocument
)已停止更新。- 复杂格式(如公式、艺术字)可能解析失败,需测试验证。
-
性能优化:
- 大文件处理:使用
POI SAX模式
(如XSSFEventBasedExcelExtractor
)避免内存溢出。 - 关闭资源:用
try-with-resources
确保流和文档对象关闭。
提取限制**: - POI可获取文本、表格、图片,但无法保留原始样式(如字体颜色)。
- 需处理加密文档:通过
POI
的EncryptedDocumentException
捕获异常。
- 大文件处理:使用
常见问题解决方案
- 乱码问题:指定编码(如
TextExtractor.setEncoding("UTF-8")
)。 - 依赖冲突:检查Maven的依赖树(
mvn dependency:tree
),排除重复库。 - 云文档解析:先通过API(如Microsoft Graph)下载为本地文件再解析。
替代方案
- docx4j:专精
.docx
,支持图表/批注等高级特性(但学习曲线陡峭)。 - OpenPDF:专注PDF,若需Word转PDF后解析可使用。
- 商业库:
Aspose.Words
(付费,功能全面,支持渲染为HTML/PDF)。
引用说明
- Apache POI官方文档:https://poi.apache.org/
- Apache Tika官网:https://tika.apache.org/
- 示例代码基于Apache License 2.0开源协议。
通过上述方法,开发者可高效解析Word内容至Java应用,推荐优先使用Apache POI处理结构化数据,或Apache Tika实现快速全文提取,实际部署前建议进行多格式兼容性测试。
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/40168.html