简体   繁体   中英

Read docx file line by line in Java

i'm trying to parse a docx file using Apache poi or docx4j but i need the text as line by line in order to store it as is. I haven't managed though to find a way to achieve that rather than paragraph text. Could you provide me with a documentation, link, solution or whatever could help me because i havent found anything that could give me a practical solution.

Thanks in advance!

Using DOCX4J, you can print every docx textual ellements using this code, maybe it can be usefull to your purpose:

public static void main(String[] args) throws Exception{

    TestPrintLines test = new TestPrintLines(); 
    String inputfilepath = System.getProperty("user.dir") + "/";
    File file = new File(inputfilepath+"yourFile.docx");
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file);
    List<Object> texts= getAllelementObjects(wordMLPackage.getMainDocumentPart(),Text.class);
    test.printLines(texts);
}

static public  List<Object> getAllelementObjects(Object obj,Class<?> toSearch) {
    List<Object> result = new ArrayList<Object>();
    if (obj instanceof JAXBElement)
        obj = ((JAXBElement<?>) obj).getValue();

    if (obj.getClass().equals(toSearch))
        result.add(obj);
    else if (obj instanceof ContentAccessor) {
        List<?> children = ((ContentAccessor) obj).getContent();
        for (Object child : children) {
            result.addAll(getAllelementObjects(child, toSearch));
        }

    }
    return result;
}

static public void printLines(List<Object> objectsList){
    for(int i = 0; i<objectsList.size(); i++) {         
        Object text = objectsList.get(i);
        Text textElement = (Text) text;
        System.out.println(textElement.getValue());
    }
}

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