700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Apache POI 读取 Word 表格数据(doc 和 docx 后缀)

Apache POI 读取 Word 表格数据(doc 和 docx 后缀)

时间:2024-03-07 12:25:14

相关推荐

Apache POI 读取 Word 表格数据(doc 和 docx 后缀)

简要

因为实习工作的原因, 需要从 word 文件中读取数据,而这些 word 文件的内容都是表格的形式。

引入 jar 包

两种方式:

通过 Maven 引入到项目中(强烈推荐这种)

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>4.1.2</version></dependency>

直接从官网下载 Jar 包

点击 Apache POI 官网。下载最新版本的 poi-bin 压缩包

读取 word 文件表格

word 文件有两种格式,分别为 doc 和 docx 文件。这两者的区别是:doc 后缀的属于 office 97- 的旧版本文件,而 docx 后缀的属于 office 以后的文件格式,也就是说,现在新版本基本都是 docx 文件格式。

在 apache poi 包中,这两个格式都需要使用不同的类去读取。

doc 后缀的 word 文件需要使用org.apache.poi.hwpf包下的类去读取。

docx 后缀的 word 文件使用的org.apache.poi.xssf包下的类去读取。

下面分别演示doc 和 docx 读取 word 表格的代码

doc 读取 word 表格数据。

private void parseDoc(String filePath) {try {// filePath 是 doc 后缀文件的绝对路径FileInputStream is = new FileInputStream(filePath);// 读取 word 文件的表单中的数据HWPFDocument hwpf = new HWPFDocument(is);Range range = hwpf.getRange();// 表单的迭代器TableIterator it = new TableIterator(range);// 遍历表格while (it.hasNext()) {Table tb = (Table) it.next();// 遍历行for (int j = 0; j < tb.numRows(); j++) {TableRow tr = tb.getRow(j);// 遍历列for (int k = 0; k < tur.numCells(); k++) {TableCell td = tr.getCell(k);// 遍历单元格中的数据for (int n = 0; n < td.numParagraphs(); n++) {// 获取单元格的数据Paragraph paragraph = td.getParagraph(n);String text = paragraph.text();System.out.println(text);}}}}} catch (Exception e) {e.printStackTrace();System.out.println("读取doc文件失败~ :" + filePath);failFilePath.add(filePath);}}

docx 读取 word 表格数据

private void parseDocx(String filePath) {try {FileInputStream is = new FileInputStream(filePath);// 读取 docx 后缀文件,获取表单迭代器XWPFDocument doc = new XWPFDocument(is);Iterator<XWPFTable> it = doc.getTablesIterator();// 遍历表格while (it.hasNext()) {XWPFTable table = it.next();// 遍历行for (XWPFTableRow tr : table.getRows()) {// 遍历列for (XWPFTableCell tableCell : tr.getTableCells()) {// 遍历单元格中的数据for (XWPFParagraph paragraph : tableCell.getParagraphs()) {// 获取单元格中的数据String text = paragraph.getParagraphText();System.out.println(text);}}}}}} catch (Exception e) {e.printStackTrace();System.out.println("读取docx文件失败~ :" + filePath);//logger.error("读取docx文件失败~ :" + filePath);failFilePath.add(filePath);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。