如何将* .doc读入JTextPane?

时间:2012-03-31 09:17:26

标签: java apache swing doc jtextpane

我正在使用apache POI来阅读Word文档。我正在使用此示例作为模板:

http://javamix.wordpress.com/2009/05/14/reading-data-from-the-doc-file-by-using-apache-poi-api/

问题是我希望内容读入JTextPane。并且HWPFDocument无法识别insertString()。

从上面链接中的示例打印到控制台的'for'语句中,如何更改它以打印到JTextPane(如果可能)?

2 个答案:

答案 0 :(得分:1)

Swing tutorial中介绍了这一点,更具体地说,请参阅“使用文本窗格的示例”一节。从该教程中复制以下代码段

String[] initString =
        { /* ...  fill array with initial text  ... */ };

String[] initStyles =
        { /* ...  fill array with names of styles  ... */ };

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
addStylesToDocument(doc);

//Load the text pane with styled text.
try {
    for (int i=0; i < initString.length; i++) {
        doc.insertString(doc.getLength(), initString[i],
                         doc.getStyle(initStyles[i]));
    }
} catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
}

您正在寻找的方法是StyledDocument#insertString方法,如上所示

答案 1 :(得分:1)

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile {
    public static void main(String[] args) {
        File file = null;
        WordExtractor extractor = null ;
        try {

            file = new File("c:\\New.doc");
            FileInputStream fis=new FileInputStream(file.getAbsolutePath());
            HWPFDocument document=new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String [] fileData = extractor.getParagraphText();
            for(int i=0;i<fileData.length;i++){
                if(fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch(Exception exep){}
    }
}