maven構建的項目-->pom.xml文件
- eclipse提供Dependencies直接添加依賴jar包的工具:直接搜索poi以及poi-ooxml即可,maven會自動依賴需要的jar包:
- poi提供microsoft office舊版本支持,eg .xls Excel
- poi-ooxml提供microsoft office新版本支持,eg .xlsx Excel
- 或者手動修改pom.xml,在添加jar包依賴的地方加入
翻過這道山,就有人聽到你的故事。
-
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi</artifactId> 4 <version>3.10-FINAL</version> 5 </dependency>
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi-ooxml</artifactId> 4 <version>3.10-FINAL</version> 5 </dependency>
java使用poi讀取doc和docx文件(maven自動導入依賴包)
於是在網上搜尋了一陣之后才發現原來doc文檔和excel一樣不能用普通的io流的方法來讀取,而是也需要用poi,於是進行了一番嘗試后,終於以正確的編碼格式讀取了這個doc文件。
在網上搜索的過程中發現doc和docx的讀取方法是不一樣的,於是順帶也學了一下docx文件的簡單讀取。
一、導包:
doc文件的讀取,需要導入poi-scratchpad的jar包和相關依賴包:
docx文件讀取,需要導入poi-ooxml的jar包和相關依賴包:
我用的是maven構建項目,相關的依賴包會自動導入,maven導包配置如下:
1 <dependency> 2 <groupId>org.apache.poi</groupId> 3 <artifactId>poi-ooxml</artifactId> 4 <version>3.8</version> 5 </dependency> 6 <dependency> 7 <groupId>org.apache.poi</groupId> 8 <artifactId>poi-scratchpad</artifactId> 9 <version>3.8</version> 10 </dependency>
二、讀取文件的代碼:
1、doc文件讀取簡單示例:
1 public static void readAndWriterTest3() throws IOException { 2 File file = new File("C:\\Users\\tuzongxun123\\Desktop\\aa.doc"); 3 String str = ""; 4 try { 5 FileInputStream fis = new FileInputStream(file); 6 HWPFDocument doc = new HWPFDocument(fis); 7 String doc1 = doc.getDocumentText(); 8 System.out.println(doc1); 9 StringBuilder doc2 = doc.getText(); 10 System.out.println(doc2); 11 Range rang = doc.getRange(); 12 String doc3 = rang.text(); 13 System.out.println(doc3); 14 fis.close(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 }
2、docx文件讀取簡單示例:
1 public static void readAndWriterTest4() throws IOException { 2 File file = new File("C:\\Users\\tuzongxun123\\Desktop\\aa.docx"); 3 String str = ""; 4 try { 5 FileInputStream fis = new FileInputStream(file); 6 XWPFDocument xdoc = new XWPFDocument(fis); 7 XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc); 8 String doc1 = extractor.getText(); 9 System.out.println(doc1); 10 fis.close(); 11 } catch (Exception e) { 12 e.printStackTrace(); 13 } 14 }
//20171218修改
我並沒有在工作中操作過word,這篇博客也只是一時興起所做,因此寫的很簡單。
而最近陸續有朋友找我詢問相關的問題,其中有好幾個都在詢問依賴包有哪些,為了避免一再回答這種問題,特將依賴包截圖:
范仁義 2017-12-30 11:28
閱讀:2631 評論:0 推薦:0 編輯