1、需求
将word文档中的内容解析,并存储到数据库中,word中有标题、有段落文字、有表格,并且这三者要保证顺序,因为还要对数据进行修改后进行导出的操作
2、所需依赖
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
</dependency>
<!-- end poi -->
3、开始解析
public String importWordExpProgram(MultipartFile file) {
//文档元素集合下标
private int docIndex = 0;
//段落集合下标
private int pIndex = 0;
//表格集合下标
private int tableIndex = 0;
try (InputStream inputStream = file.getInputStream()) {
XWPFDocument xdoc = new XWPFDocument(inputStream);
//拿到word文档中的元素集合、段落集合、表格集合
List<IBodyElement> bodyElementList = xdoc.getBodyElements();
List<XWPFParagraph> paragraphList = xdoc.getParagraphs();
List<XWPFTable> tableList = xdoc.getTables();
//遍历元素集合
for (; docIndex < bodyElementList.size(); docIndex++) {
//如果元素属于段落类型
if (bodyElementList.get(docIndex).getElementType() == BodyElementType.PARAGRAPH) {
//对段落进行操作
System.out.println(paragraphList.get(pIndex).getText());
pIndex++;
} else if (bodyElementList.get(docIndex).getElementType() == BodyElementType.TABLE) {
//如果元素属于表格类型,对表格进行解析,先拿到表格所有的行
List<XWPFTableRow> rows = tableList.get(tableIndex).getRows();
tableIndex++;
//遍历表格中的每个元素
for (int i = 0; i < rows.size(); i++) {
List<XWPFTableCell> tableCells = rows.get(i).getTableCells();
for (int j = 0; j < tableCells.size(); j++) {
//对表格单元值进行操作
System.out.println(tableCells.get(j).getText());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return '解析word文档成功~';
}
这是最基础的解析工作,可以按照word中的顺序依次打印文字和表格,可以配合其它代码来读取标题等级并分批次将数据保存到数据库中。