简体   繁体   中英

How do I read *.doc into JTextPane?

I'm using the apache POI to read Word documents. I'm using this example as a template:

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

The problem is I want the contents to read into a JTextPane. And insertString() is not recognized by HWPFDocument.

From the 'for' statement that prints to console from the example in the link above, how do change it to print to the JTextPane (if possible)?

This is covered in the Swing tutorial , more in particular in the section 'An example of using a text pane'. The following code snippet is copied from that 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.");
}

The method you are looking for is the StyledDocument#insertString method, as illustrated above

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){}
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM