---
title: "POI操作WORD"
author: "chengzhi_hong"
date: "2012-01-01T15:04:49Z"
tags: []
categories: ["企业架构"]
slug: "poi-word"
draft: false
lastmod: "2012-01-01T15:04:49Z"
id: 1332887
url: "https://wamp.iteye.com/blog/1332887"
---

通过下面的两种方法可以从文档里读取所有字符性的内容（忽略字符的属性）。  
通过输出流来写到文本文件中。  
public static void getWordContent(String fileName) throws Exception{  
   FileInputStream in = new FileInputStream(new File(fileName));  
   WordExtractor extractor = new WordExtractor(in);  
   String text = extractor.getText();  
   FileWriter f = new FileWriter(new File("e:\\\\Test.txt"));  
   f.write(text);  
   f.close();  
}

public static void getWordDetail(String fileName) throws Exception{  
   FileInputStream in = new FileInputStream(new File(fileName));  
   FileOutputStream out = new FileOutputStream(new File("e:\\\\test.txt"));  
   HWPFDocument doc = new HWPFDocument(in);  
   System.out.println("文档长度:"+doc.characterLength());  
   Range range = doc.getRange();  
   String text = range.text();  
   System.out.println(text);  
   byte\[] \_inBuf = text.getBytes();  
   out.write(\_inBuf);  
   out.close();  
}

如果要每个字符的样式，可以用CharaterRun这个类，它的方法专门用于获得字符和判断的样式。  
如:  
import java.io.File;  
import java.io.FileInputStream;  
import org.apache.poi.hwpf.HWPFDocument;  
import org.apache.poi.hwpf.usermodel.Range;  
import org.apache.poi.hwpf.usermodel.CharacterRun;  
public class Angle {  
public static void getAwayAngle(String fileName) throws Exception {  
   FileInputStream in = new FileInputStream(new File(fileName));  
   HWPFDocument doc = new HWPFDocument(in);  
   int length = doc.characterLength();  
   StringBuffer sb = new StringBuffer();  
   for (int i = 0; i &lt; length-1; i++) {  
   Range range = new Range(i, i+1, doc);  
       //之所以用这个构造方法，是因为整篇文章的字符判断不准确。只好一个字符一个字符的来判断。  
       //而且API的说明文字相当的不全。  
   for(int j=0;j&lt;range.numCharacterRuns();j++){  
     CharacterRun cr=range.getCharacterRun(j);  
     if(cr.getSubSuperScriptIndex()==0)//getSubSuperScriptIndex()这个方法来判断是否是上下角标  
     sb.append(range.text());  
   }  
   }  
   System.out.println(sb.toString());  
}  
public static void main(String\[] args) {  
   try {  
   getAwayAngle("e:\\\\test1.doc");  
   } catch (Exception e) {  
   e.printStackTrace();  
   }  
}  
}

在POI中Range这个类是核心类。里面有很多方法用来操作WORD文档。  
还有其它比较重要的类Section和Paragraph等。