使用時間:4小時
使用poi方法將word中的內容提取出來,並輸出到控制台或者存儲到數據庫
poi.jar下載地址:https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.17-20170915.tar.gz
需要導入的包

根據標題和內容字體大小的不同,尋找所需要的段落和標題,並判斷是標題還是內容。
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; } } } }
參考來源:https://www.cnblogs.com/wys-373/p/10568322.html