java使用poi讀取doc和docx文件的實現示例
這幾天在學習java io流的東西,有一個網友看到博客后問了一個問題,就是說他的doc文檔為什么用我所說的方法死活就是亂碼。
我一開始以為是他方法問題,結果自己試了之后發現和他的結果一樣也是亂碼。
于是在網上搜尋了一陣之后才發現原來doc文檔和excel一樣不能用普通的io流的方法來讀取,而是也需要用poi,于是進行了一番嘗試后,終于以正確的編碼格式讀取了這個doc文件。
在網上搜索的過程中發現doc和docx的讀取方法是不一樣的,于是順帶也學了一下docx文件的簡單讀取。
一、導包:
doc文件的讀取,需要導入poi-scratchpad的jar包和相關依賴包:
docx文件讀取,需要導入poi-ooxml的jar包和相關依賴包:
我用的是maven構建項目,相關的依賴包會自動導入,maven導包配置如下:
<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>
二、讀取文件的代碼:
1、doc文件讀取簡單示例:
public static void readAndWriterTest3() throws IOException { File file = new File('C:Userstuzongxun123Desktopaa.doc'); String str = ''; try { FileInputStream fis = new FileInputStream(file); HWPFDocument doc = new HWPFDocument(fis); String doc1 = doc.getDocumentText(); System.out.println(doc1); StringBuilder doc2 = doc.getText(); System.out.println(doc2); Range rang = doc.getRange(); String doc3 = rang.text(); System.out.println(doc3); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
2、docx文件讀取簡單示例:
public static void readAndWriterTest4() throws IOException { File file = new File('C:Userstuzongxun123Desktopaa.docx'); String str = ''; try { FileInputStream fis = new FileInputStream(file); XWPFDocument xdoc = new XWPFDocument(fis); XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc); String doc1 = extractor.getText(); System.out.println(doc1); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
我并沒有在工作中操作過word,這篇博客也只是一時興起所做,因此寫的很簡單。
而最近陸續有朋友找我詢問相關的問題,其中有好幾個都在詢問依賴包有哪些,為了避免一再回答這種問題,特將依賴包截圖:
到此這篇關于java使用poi讀取doc和docx文件的實現示例的文章就介紹到這了,更多相關java poi讀取doc和docx內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: