java讀取word文檔,提取標(biāo)題和內(nèi)容的實(shí)例
使用的工具為poi,需要導(dǎo)入的依賴(lài)如下
<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>
我采用的分離方式是根據(jù)字體大小判斷。尋找字體大小和下一段大小不同的段落,再一次判斷第二段和后邊的是否相同,相同則繼續(xù),不同則輸出標(biāo)題和內(nèi)容。
因?yàn)橛械奈臋n中存在多個(gè)標(biāo)題,所以我在開(kāi)始加了判斷,如果連續(xù)三個(gè)段落的字體大小遞減則該段落跳過(guò)。
而且文章存在目錄,經(jīng)過(guò)測(cè)試發(fā)現(xiàn)目錄的String中都包含了“HYPERLINK” 所以如果段落中包含該字符串則跳過(guò)。
代碼如下:
package com.w.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
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.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import com.example.model.Policy_content;
public class GetWord {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
List<Policy_content> list = new ArrayList<>();
InputStream is = new FileInputStream(new File("文件路徑")); //需要將文件路更改為word文檔所在路徑。
POIFSFileSystem fs = new POIFSFileSystem(is);
HWPFDocument document = new HWPFDocument(fs);
Range range = document.getRange();
CharacterRun run1 = null;//用來(lái)存儲(chǔ)第一行內(nèi)容的屬性
CharacterRun run2 = null;//用來(lái)存儲(chǔ)第二行內(nèi)容的屬性
int q=1;
for (int i = 0; i < range.numParagraphs()-1; i++) {
Paragraph para1 = range.getParagraph(i);// 獲取第i段
Paragraph para2 = range.getParagraph(i+1);// 獲取第i段
int t=i; //記錄當(dāng)前分析的段落數(shù)
String paratext1 = para1.text().trim().replaceAll("\r\n", ""); //當(dāng)前段落和下一段
String paratext2 = para2.text().trim().replaceAll("\r\n", "");
run1=para1.getCharacterRun(0);
run2=para2.getCharacterRun(0);
if (paratext1.length() > 0&¶text2.length() > 0) {
//這個(gè)if語(yǔ)句為的是去除大標(biāo)題,連續(xù)三個(gè)段落字體大小遞減就跳過(guò)
if(run1.getFontSize()>run2.getFontSize()&&run2.getFontSize()>range.getParagraph(i+2).getCharacterRun(0).getFontSize()) {
continue;
}
//連續(xù)兩段字體格式不同
if(run1.getFontSize()>run2.getFontSize()) {
String content=paratext2;
run1=run2; //從新定位run1 run2
run2=range.getParagraph(t+2).getCharacterRun(0);
t=t+1;
while(run1.getFontSize()==run2.getFontSize()) {
//連續(xù)的相同
content+=range.getParagraph(t+1).text().trim().replaceAll("\r\n", "");
run1=run2;
run2=range.getParagraph(t+2).getCharacterRun(0);
t++;
}
if(paratext1.indexOf("HYPERLINK")==-1&&content.indexOf("HYPERLINK")==-1) {
System.out.println(q+"標(biāo)題"+paratext1+"\t內(nèi)容"+content);
i=t;
q++;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
補(bǔ)充知識(shí):Java poi導(dǎo)入word文件提取內(nèi)容
一、需求描述
java web項(xiàng)目從前臺(tái)上傳word格式文件,后臺(tái)接收文件并提取word內(nèi)容保存至數(shù)據(jù)庫(kù)。
二、依賴(lài)jar包
這里操作的是maven項(xiàng)目,所有依賴(lài)jar包均可到maven倉(cāng)庫(kù)進(jìn)行免費(fèi)下載。具體如下:

三、后臺(tái)代碼
這里的java_web項(xiàng)目采用SpringMVC的內(nèi)置文件上傳方式進(jìn)行接收解析,具體如下:
/**
* 提取word文件內(nèi)容
* @param file
* @param request
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping(value = "/getPapers", method = RequestMethod.POST, produces = { "text/html;charset=utf-8" })
@ResponseBody
private Object getPapers(@RequestParam("file") MultipartFile multfile,HttpServletRequest request) throws IllegalStateException, IOException {
// 獲取文件名
String fileName = multfile.getOriginalFilename();
//判斷是否為word類(lèi)型文件
if (!fileName.endsWith(".doc") && !fileName.endsWith(".docx")) {
System.out.println("此文件不是word文件!");
}
//當(dāng)前系統(tǒng)的臨時(shí)文件地址
String realPath = request.getSession().getServletContext().getRealPath("/static/app/appkmbgszh/uploadFile");
// 用uuid作為文件名,防止生成的臨時(shí)文件重復(fù)
String fileAdd = UUID.randomUUID().toString() + ".docx";
// 構(gòu)建一個(gè)臨時(shí)文件
File uploadFile = new File(realPath, fileAdd);
//將上傳的MultipartFile格式文件轉(zhuǎn)換為創(chuàng)建的新文件
multfile.transferTo(uploadFile);
//獲取新文件的絕對(duì)路徑
String filePath = uploadFile.getAbsolutePath();
String buffer = "";
JSONObject msg = new JSONObject();
try {
InputStream inIo = new FileInputStream(uploadFile);
//提取文本內(nèi)容
if (fileName.endsWith(".doc")) {
WordExtractor ex = new WordExtractor(inIo);
buffer = ex.getText();
ex.close();
} else if (fileName.endsWith(".docx")) {
OPCPackage opcPackage = POIXMLDocument.openPackage(filePath);
POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
buffer = extractor.getText();
extractor.close();
}
//刪除上傳存放的臨時(shí)文件
uploadFile.delete();
msg.put("status", true);
msg.put("msg", buffer);
} catch (Exception e) {
e.printStackTrace();
msg.put("status", false);
msg.put("msg", "文件內(nèi)容提取失敗");
}
return retString(msg);
}
/**
* json格式化;
* @param ret
* @return
*/
private String retString(JSONObject ret) {
String jsoStr = "";
try {
jsoStr = JSON.json(ret);
} catch (IOException e) {
e.printStackTrace();
return jsoStr;
}
return jsoStr;
}
以上這篇java讀取word文檔,提取標(biāo)題和內(nèi)容的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java的LinkedHashMap的實(shí)現(xiàn)原理詳解
這篇文章主要介紹了Java的LinkedHashMap的實(shí)現(xiàn)原理詳解,???LinkedHashMap是Map接口的哈希表和鏈接列表實(shí)現(xiàn),具有可預(yù)知的迭代順序,此實(shí)現(xiàn)提供所有可選的映射操作,并允許使用null值和null鍵,此類(lèi)不保證映射的順序,特別是它不保證該順序恒久不變,需要的朋友可以參考下2023-09-09
SpringBoot快速搭建實(shí)現(xiàn)三步驟解析
這篇文章主要介紹了SpringBoot快速搭建實(shí)現(xiàn)三步驟解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
springMvc注解之@ResponseBody和@RequestBody詳解
本篇文章主要介紹了springMvc注解之@ResponseBody和@RequestBody詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
劍指Offer之Java算法習(xí)題精講鏈表與數(shù)組專(zhuān)項(xiàng)訓(xùn)練
跟著思路走,之后從簡(jiǎn)單題入手,反復(fù)去看,做過(guò)之后可能會(huì)忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會(huì)發(fā)現(xiàn)質(zhì)的變化2022-03-03
解決JSON.toJSONString首字母大小寫(xiě)的問(wèn)題
這篇文章主要介紹了解決JSON.toJSONString首字母大小寫(xiě)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

