zoukankan      html  css  js  c++  java
  • POI操作WORD

    通过下面的两种方法可以从文档里读取所有字符性的内容(忽略字符的属性)。
    通过输出流来写到文本文件中。
    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 < length-1; i++) {
       Range range = new Range(i, i+1, doc);
           //之所以用这个构造方法,是因为整篇文章的字符判断不准确。只好一个字符一个字符的来判断。
           //而且API的说明文字相当的不全。
       for(int j=0;j<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等。
    POI没有中文的API,英文的API说明相当不全,方法多数只能靠猜。Apache太不负责任了。
  • 相关阅读:
    17张程序员壁纸推荐,是否有一张你喜欢的?
    学会了这些英文单词,妈妈再也不用担心我学不会Python
    小白学习Python英语基础差怎么办,都帮你想好拉!看这里
    自动化测试学习防踩坑手册,测试人员人手一份
    Selenium自动化结合Mysql数据项目实战操作
    解除你学习Python自动化测试框架的所有疑惑,开启学习直通车
    数据库管理软件navicate12的激活和安装
    修改文件版本号方法
    Json的数据映射(基于LitJson)
    VMware 虚拟机安装黑屏问题
  • 原文地址:https://www.cnblogs.com/monica/p/1603636.html
Copyright © 2011-2022 走看看