1、所需jar包如下
读取写入word文件需要:poi-3.9.jar、poi-ooxml-3.9.jar、poi-scratchpad-3.9.jar、xmlbeans-2.3.0.jar
2、jar包来源方式
可以从apache官方网站下载 http://poi.apache.org/download.html
也可以通过maven方式下载:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.8</version>
</dependency>
3、解析文件源码
package com.poi;
import java.io.FileInputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class WordParse {
public static final String FILE_PATH = "D:\\test.doc";
public static void main(String[] args) {
// parseWordByParagraphs(FILE_PATH);
parseTableContent(FILE_PATH);
}
/**
* 以段的方式解析word文档
*
* <pre>
* 1、表格外的内容每个回车换行符为一个段
* 2、表格中的每个单元格为一个段
* 3、表格中的单元格中的内容每存在一个回车换行符又为一个段
* </pre>
*
* @param wordPath
*/
public static void parseWordByParagraphs(String wordPath) {
try {
// 将word转换成poi文档格式
HWPFDocument hwpf = new HWPFDocument(new POIFSFileSystem(new FileInputStream(wordPath)));
// 得到文档的读取范围
Range range = hwpf.getRange();
for (int i = 0; i < range.numParagraphs(); i++) {
Paragraph para = range.getParagraph(i);
String s = para.text().trim();
System.out.println("段" + i + ": " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析word中表格的内容
*
* @param wordPath
*/
public static void parseTableContent(String wordPath) {
try {
// 将word转换成poi文档格式
HWPFDocument hwpf = new HWPFDocument(new POIFSFileSystem(new FileInputStream(wordPath)));
// 得到文档的读取范围
Range range = hwpf.getRange();
TableIterator it = new TableIterator(range);
// 迭代文档中的内容
String cellContent = "";
while (it.hasNext()) {
Table table = (Table) it.next();
// 以行的方式迭代表格,默认从第0行开始
for (int i = 0, rows = table.numRows(); i < rows; i++) {
TableRow tr = table.getRow(i);
// 迭代每一行中的列,默认从第0列开始
for (int j = 0, cells = tr.numCells(); j < cells; j++) {
TableCell td = tr.getCell(j);
cellContent = "";
// 获取单元格内容
for (int k = 0, paragraphs = td.numParagraphs(); k < paragraphs; k++) {
Paragraph para = td.getParagraph(k);
String content = para.text().trim();
cellContent += content;
}
System.out.println("第" + i + "行,第" + j + "列:" + cellContent);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
poi解析word
最新推荐文章于 2024-07-26 16:03:13 发布