import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class poi_word {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream(new File("path")); //读取文件
POIFSFileSystem fs = new POIFSFileSystem(is);
@SuppressWarnings("resource")
HWPFDocument document = new HWPFDocument(fs);
Range range = document.getRange(); //存储word内容到document中
for (int i = 0; i < range.numParagraphs()-2; i++) { //numparagraphs代表段落总数
int setparagraph=i; //记录当前段落
Paragraph para_1 = range.getParagraph(i);// 获取第i段
Paragraph para_2 = range.getParagraph(i+1);// 获取第i+1段
Paragraph para_3 = range.getParagraph(i+2);// 获取第i+2段
String paratext1 = para_1.text().trim().replaceAll("\r\n", ""); //当前段落的内容并去除换行
String paratext2 = para_2.text().trim().replaceAll("\r\n", ""); //当前段落的内容并去除换行
CharacterRun run1=para_1.getCharacterRun(0);
CharacterRun run2=para_2.getCharacterRun(0);
CharacterRun run3=para_3.getCharacterRun(0); //段落属性
if (paratext1.length() > 0&¶text2.length() > 0) {
if(run1.getFontSize()>run2.getFontSize()&&run2.getFontSize()>run3.getFontSize()) continue; // 当连续三个及以上的字体大小不同的段落存在时则跳过当前循环,直到两个段落存在(找到小标题和内容)
String content="";
if(run1.getFontSize()>=run2.getFontSize()) { //当两段内容字体大小为大于时 则为标题和内容 相等时则同为内容
content +=paratext2; //第i+1段为内容
run1=run2;
run2=run3; //顺序重新定位段落
setparagraph++;
}
System.out.println(paratext1+"\t"+content);
i=setparagraph;
}
}
}
}