• 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太不负责任了。
  • 相关阅读:
    Auto X2021 K Increasing Sequence
    拉普拉斯平滑处理 Laplace Smoothing
    博学之
    Python-生成音乐-pyshnth
    Python-Kivy ImportError: DLL load failed: 找不到指定的模块
    Python-Word模板填充-docxtpl
    Python-文字转语音-pyttsx3
    Virtual Box中Ubuntu使用"桥接网卡"不能联网而使用"网络地址转换(NAT)"却可以上网
    STM32的HAL库中的DMA_FLAG_TCIF3_7等几个宏定义的含义
    Linux下编写互相通信的驱动模块并将其加入到内核中
  • 原文地址:https://www.cnblogs.com/monica/p/1603636.html
Copyright © 2020-2023  润新知