zoukankan      html  css  js  c++  java
  • java使用poi读取doc和docx文件(maven自动导入依赖包)

    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,这篇博客也只是一时兴起所做,因此写的很简单。 
    而最近陆续有朋友找我询问相关的问题,其中有好几个都在询问依赖包有哪些,为了避免一再回答这种问题,特将依赖包截图: 
    这里写图片描述

  • 相关阅读:
    微信小程序退款【证书的使用】
    生成随机位数的UUID
    弹出层-layui
    load加载层-layui
    form-layui
    table-layui
    下拉列表模仿placeholder效果
    .net core 2.0 Unable to convert MySQL date/time to System.DateTime
    .net core Include问题
    .net core 2.0 配置Session
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/8147650.html
Copyright © 2011-2022 走看看