使用POI对word文件进行读取

目标:用poi对doc、docx类型文件读取内容

jar包:
poi-3.13-20150929.jar
poi-ooxml-3.13-20150929.jar
poi-ooxml-schemas-3.13-20150929.jar
poi-scratchpad-3.13-20150929.jar
xmlbeans-2.6.0.jar

编写函数,录入文件名称,得到该word文件的段落数,根据段落数输出文本。

 

class如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class DocumentUtil {
 private static XWPFDocument readDocx(String fileName) throws IOException{
        XWPFDocument xdoc = new XWPFDocument(POIXMLDocument.openPackage(fileName));
  return xdoc;
 }
 
 private static HWPFDocument readDoc(String fileName) throws IOException{
  InputStream is = new FileInputStream(fileName);
        HWPFDocument xdoc = new HWPFDocument(is);
        return xdoc;
 }
 
 public static int paragraphNums(String fileName) throws IOException{
  int result=0;
  if(fileName.endsWith(".docx")){
   result=readDocx(fileName).getParagraphs().size();
  }else if(fileName.endsWith(".doc")){
   result=readDoc(fileName).getRange().numParagraphs();
  }
  return result;
 }
 
 public static String paragraphText(String fileName,int numb) throws IOException{
  String result=null;
  if(fileName.endsWith(".docx")){
   result=readDocx(fileName).getParagraphs().get(numb).getText();
  }else if(fileName.endsWith(".doc")){
   result=readDoc(fileName).getRange().getParagraph(numb).text();
  }
  return result;
 }
 
 public static void main(String[] args) throws IOException {
  String fileName="e:\\衡水市局关于国地税联合办税进一步改进服务的通知的落实情况.docx";
  int numB=paragraphNums(fileName);
  for(int i=0;i<numB;i++){
   String textP=paragraphText(fileName,i);
   System.out.println(textP);
   System.out.println("--------");
  }
 }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值