提取Word中的标题以及做标记的内容

需要依赖:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>

<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.core</artifactId>
<version>1.0.6</version>
</dependency>

代码:
public static void main(String[] args) throws IOException {
try {
/* 一个文档包含多个段落,一个段落包含多个Runs,一个Runs包含多个Run,Run是文档的最小单元
获取所有段落:List<XWPFParagraph> paragraphs = word.getParagraphs();
获取一个段落中的所有Runs:List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
获取一个Runs中的一个Run:XWPFRun run = xwpfRuns.get(index);
XWPFRun--代表具有相同属性的一段文本*/

//获取文档的所有段落
InputStream is = new FileInputStream(new File("C:\\Users\\Desktop\\测试.docx")); //读取文件
XWPFDocument doc = new XWPFDocument(is);
List<XWPFParagraph> xwpfParagraphs = doc.getParagraphs();
//获取段落内容
for (XWPFParagraph xwpfParagraph : xwpfParagraphs) {
//当前段落的属性
//CTPPr pr = para.getCTP().getPPr();
// System.out.println(xwpfParagraph.getText()+"********************");
List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
for(XWPFRun xwpfRun:xwpfRuns){
// System.out.println(xwpfRun+"--------------");
}
}

List<String> list = new ArrayList<String>(); //获取所有标题

for (XWPFParagraph graph : xwpfParagraphs) {
String text = graph.getParagraphText();
System.out.println(text);
if(text.contains("*")){
//解析该段落里面的内容
int j=0;
for(int i=-1; i<=text.lastIndexOf("*");++i)
{
//获取开始出现*号位置
i=text.indexOf("*",i);
//获取第二个出现*号位置
j=text.indexOf("*",i+1);
String substring = text.substring(i+1, j);
System.out.println("截取内容:"+substring);
i=j; //做标记,从此处开始重新查找
}

}

String style = graph.getStyle();
if ("1".equals(style) || "2".equals(style) || "3".equals(style) || "4".equals(style) || "5".equals(style) || "6".equals(style) || "7".equals(style) || "8".equals(style) ) {
//System.out.println(text+"--["+style+"]");
list.add("["+style+"]、"+text);
}
}
for(String string:list){
System.out.println(string+"--------------");
}
}catch (Exception e){
e.printStackTrace();
}
}

文档内容:
提取Word中的标题以及做标记的内容

 

 效果图:

提取Word中的标题以及做标记的内容

 

 



上一篇:云边端EasyGBS视频智能分析算法接入方案


下一篇:java-poi 批量导入excel数据