之前做過(guò)用java讀取word文檔,獲取word文本內(nèi)容。
但發(fā)現(xiàn)docx的支持,doc就異常了。
后來(lái)找了很多資料發(fā)現(xiàn)是解析方法不一樣。
首先要導(dǎo)入poi相關(guān)的jar包
我用的是maven,pom.xml引入如下:
1
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-ooxml</ artifactId > < version >3.8</ version > </ dependency > < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi-scratchpad</ artifactId > < version >3.8</ version > </ dependency > |
java獲取word文本內(nèi)容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public BaseResp getParsedTxt(MultipartFile file) throws Exception { BaseResp br= new BaseResp( "200" , "" ) ; String textType = file.getContentType(); String txt = "" ; if (textType.equals(TXT_TYPE)){ String code = getCharset(file); txt = new String(file.getBytes(),code); } else if (textType.equals(DOC_TYPE)){ HWPFDocument doc = new HWPFDocument(file.getInputStream()); Range rang = doc.getRange(); txt = rang.text(); System.out.println(txt); } else if (textType.equals(DOCX_TYPE)){ File uFile = new File( "tempFile.docx" ); if (!uFile.exists()){ uFile.createNewFile(); } FileCopyUtils.copy(file.getBytes(), uFile); OPCPackage opcPackage = POIXMLDocument.openPackage( "tempFile.docx" ); POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage); txt= extractor.getText(); uFile.delete(); } else { br = new BaseResp( "300" , "上傳文件格式錯(cuò)誤,請(qǐng)上傳.txt或者.docx" ); return br; } br.setDatas(txt); return br; } |
功能實(shí)現(xiàn)了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。