随笔记录①—利用poi读取Word中的标题和内容
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
随笔记录①—利⽤poi读取Word中的标题和内容
使⽤时间:4⼩时
使⽤poi⽅法将word中的内容提取出来,并输出到控制台或者存储到数据库
poi.jar下载地址:
需要导⼊的包
根据标题和内容字体⼤⼩的不同,寻找所需要的段落和标题,并判断是标题还是内容。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hwpf.HWPFDocument;
import ermodel.CharacterRun;
import ermodel.Paragraph;
import ermodel.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;
}
}
}
}。