java讀取word文檔,獲取文本內容,保留基本的換行格式。
java用POI對word進行解析。所需jar包,用maven引入
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.2-FINAL</version>
</dependency>
前端用webuploader上傳控件,限制上傳文件類型僅支持text和word.
1 accept: { 2 title: 'text', 3 extensions: 'txt,docx', 4 mimeTypes: 'text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document' 5 }
后台MultipartFile接收文件,根據ContentType區分文件類型,區分解析獲取文件內容。
word解析:
1 File uFile = new File("tempFile.docx"); 2 if(!uFile.exists()){ 3 uFile.createNewFile(); 4 } 5 FileCopyUtils.copy(file.getBytes(), uFile); 6 OPCPackage opcPackage = POIXMLDocument.openPackage("tempFile.docx"); 7 POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage); 8 txt= extractor.getText();
txt為word的文本內容