溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在java中使用poi讀取doc文件

發(fā)布時間:2021-04-09 17:12:54 來源:億速云 閱讀:1019 作者:Leah 欄目:編程語言

怎么在java中使用poi讀取doc文件?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

一、導包:

doc文件的讀取,需要導入poi-scratchpad的jar包和相關依賴包:

怎么在java中使用poi讀取doc文件

docx文件讀取,需要導入poi-ooxml的jar包和相關依賴包:

怎么在java中使用poi讀取doc文件

我用的是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:\\Users\\tuzongxun123\\Desktop\\aa.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:\\Users\\tuzongxun123\\Desktop\\aa.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,這篇博客也只是一時興起所做,因此寫的很簡單。

而最近陸續(xù)有朋友找我詢問相關的問題,其中有好幾個都在詢問依賴包有哪些,為了避免一再回答這種問題,特將依賴包截圖:

怎么在java中使用poi讀取doc文件

看完上述內容,你們掌握怎么在java中使用poi讀取doc文件的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI