Example usage for org.apache.poi.xwpf.usermodel XWPFDocument getParagraphs

List of usage examples for org.apache.poi.xwpf.usermodel XWPFDocument getParagraphs

Introduction

In this page you can find the example usage for org.apache.poi.xwpf.usermodel XWPFDocument getParagraphs.

Prototype

@Override
public List<XWPFParagraph> getParagraphs() 

Source Link

Usage

From source file:IsiXhosa_spellchecker.Spellchecker.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // Open file from machine
    int returnVal = fileChooser.showOpenDialog(this);
    boolean English = jRadioButton1.isSelected();
    if (English)/*from w  w w .  j  av a  2s  .  c o m*/
        instruction.setText("Spellcheck to check for errors");
    else
        instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha");
    instruction.setForeground(Color.BLUE);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String name = file.getName();
        String ext = name.substring(name.indexOf("."), name.length());

        try {
            // What to do with the file, e.g. display it in a TextArea
            if (highlightSet) {
                highlighter.removeAllHighlights();
            }
            if (name.endsWith(".docx")) {
                FileInputStream fis = new FileInputStream(file.getAbsolutePath());
                XWPFDocument docx = new XWPFDocument(fis);
                List<XWPFParagraph> pars = docx.getParagraphs();
                String toDisplay = "";
                for (XWPFParagraph para : pars) {
                    toDisplay += para.getText() + "\n";
                }

                textArea.setText(toDisplay);
                text = textArea.getText();
            } else {
                textArea.read(new FileReader(file.getAbsolutePath()), null);
                text = textArea.getText(); //for controlling the displayed text
            }
        } catch (IOException ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    }
    //Resets globals used by other buttons such as ignoreAll
    pos = 0;
    sentNo = 0;
    wordNo = 0;

}

From source file:isizulu_spellchecker.Spellchecker.java

private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
    // TODO add your handling code here:          
    int returnVal = fileChooser.showOpenDialog(this);
    if (language)
        instruction.setText("Click run to check for errors");
    else//from w  w w  .  ja v  a  2  s .  co m
        instruction.setText("Cofa uSebenzisa ukuze uhlole amaphutha");
    instruction.setForeground(Color.BLUE);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String name = file.getName();
        String ext = name.substring(name.indexOf("."), name.length());

        try {
            // What to do with the file, e.g. display it in a TextArea
            if (highlightSet) {
                highlighter.removeAllHighlights();
            }
            if (name.endsWith(".docx")) {
                FileInputStream fis = new FileInputStream(file.getAbsolutePath());
                XWPFDocument docx = new XWPFDocument(fis);
                List<XWPFParagraph> pars = docx.getParagraphs();
                String toDisplay = "";
                for (XWPFParagraph para : pars) {
                    toDisplay += para.getText() + "\n";
                }

                textArea.setText(toDisplay);
                text = textArea.getText();
            } else {
                textArea.read(new FileReader(file.getAbsolutePath()), null);
                text = textArea.getText(); //for controlling the displayed text
            }
        } catch (IOException ex) {
            System.out.println("problem accessing file" + file.getAbsolutePath());
        }
    }
    //Resets globals used by other buttons such as ignoreAll
    pos = 0;
    sentNo = 0;
    wordNo = 0;
}

From source file:javaapplication1.AnotherPOI.java

public static void replaceText(String findText, String replaceText) {
    try {/*w  w  w.ja  v a2s  .c  om*/
        XWPFDocument doc = new XWPFDocument(OPCPackage.open("D:\\template.docx"));
        for (XWPFParagraph p : doc.getParagraphs()) {

            List<XWPFRun> runs = p.getRuns();
            if (runs != null) {
                for (XWPFRun r : runs) {
                    String text = r.getText(0);
                    if (text != null && text.contains(findText)) {
                        text = text.replace(findText, replaceText);
                        r.setText(text, 0);
                    }
                }
            }
        }
        for (XWPFTable tbl : doc.getTables()) {
            for (XWPFTableRow row : tbl.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        for (XWPFRun r : p.getRuns()) {
                            String text = r.getText(0);
                            if (text.contains(findText)) {
                                text = text.replace(findText, replaceText);
                                r.setText(text);
                            }
                        }
                    }
                }
            }
        }
        doc.write(new FileOutputStream("D:\\result.docx"));
    } catch (IOException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidFormatException ex) {
        Logger.getLogger(AnotherPOI.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:kz.service.DocumentReader.java

public static String readDocxFile(String fileName) {

    try {/*from   w w  w  .j  a v a 2 s  .  c  o  m*/
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file.getAbsolutePath());
        StringBuffer content = new StringBuffer();

        XWPFDocument document = new XWPFDocument(fis);
        XWPFStyles styles = document.getStyles();

        List<XWPFParagraph> paragraphs = document.getParagraphs();
        List<XWPFTable> tables = document.getTables();
        List<XWPFPictureData> pictures = document.getAllPictures();

        //int Picture_ID = 0;
        for (XWPFPictureData picture : pictures) {
            //XWPFPictureData picture = pictures.get(Picture_ID);
            System.out.println("Picture: " + picture.getFileName());
            byte[] pictureData = picture.getData();
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(pictureData));
            ImageIO.write(image, picture.getFileName(), file);
            content.append("<p>");
            content.append("Here must be image");
            content.append("</p>");
            //Picture_ID++;
        }

        Iterator<IBodyElement> bodyElementIterator = document.getBodyElementsIterator();
        int Table_ID = 0;
        int Paragraph_ID = 0;
        while (bodyElementIterator.hasNext()) {

            IBodyElement element = bodyElementIterator.next();
            System.out.println(element.getElementType().name());//prints Element type name

            if ("TABLE".equalsIgnoreCase(element.getElementType().name())) {

                content.append("<table>");
                XWPFTable table = tables.get(Table_ID);
                CTTbl cttbl = table.getCTTbl();
                CTTblPr cttblPr = cttbl.getTblPr();

                List<XWPFTableRow> tblRows = table.getRows();
                for (XWPFTableRow tblRow : tblRows) {
                    content.append("<tr>");
                    List<XWPFTableCell> tblCells = tblRow.getTableCells();
                    for (XWPFTableCell tblCell : tblCells) {
                        content.append("<td>");
                        content.append(tblCell.getText());
                        content.append("</td>");
                    }
                    content.append("</tr>");
                }
                content.append("</table>");
                Table_ID++;

            } else if ("PARAGRAPH".equalsIgnoreCase(element.getElementType().name())) {

                XWPFParagraph paragraph = paragraphs.get(Paragraph_ID);

                String styleClass = null;
                if (paragraph.getStyleID() != null) {
                    content.append("<p class=''>");
                    XWPFStyle style = styles.getStyle(paragraph.getStyleID());
                    if (style != null && style.getName() != null) {
                        //here will be code creation of tag with class style
                    }
                } else {
                    content.append("<p>");
                }
                content.append(paragraph.getText());
                content.append("</p>");
                Paragraph_ID++;

            }
        }

        fis.close();
        return content.toString();
    } catch (Exception e) {
        return e.toString();
    }

}

From source file:msoffice.ReadWord.java

public static void main(String[] args) {

    try {//w w w. j a v  a2  s .c  o  m
        FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx");
        XWPFDocument docx = new XWPFDocument(fis);

        List<XWPFParagraph> paragraphList = docx.getParagraphs();
        int nump = paragraphList.size();
        System.out.println(nump);

        for (int x = 0; x < paragraphList.size(); x++) {

        }

        for (XWPFParagraph paragraph : paragraphList) {

            String text = paragraph.getText();

            XWPFRun rh = paragraph.createRun();

            if (text.contains("unidad")) {
                text = text.replace("unidad", "CICTE/W-6.a/02.00");
                paragraph.removeRun(8);
                rh.setText(text);

            }
            if (text.contains("receptor")) {
                text = text.replace("receptor",
                        "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito");

            }

            if (text.contains("asunto")) {
                text = text.replace("asunto", "Sobre articulo de MG (Armamento) y apoyo de elemento tecnico.");

            }

            if (text.contains("referencia")) {
                text = text.replace("referencia", "Oficio N289/CICTE del 01 julio de 2015.");

            }

            if (text.contains("cuerpo")) {
                text = text.replace("cuerpo",
                        "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prestamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n"
                                + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n"
                                + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal.");

            }

            System.out.println(text);
            docx.write(new FileOutputStream("OFICIO.docx"));
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:msoffice.WriteinTemplate.java

public static void main(String[] args) throws FileNotFoundException, InvalidFormatException, IOException {

    FileInputStream fis = new FileInputStream("H:\\OFICIOTEMPLATE.docx");
    XWPFDocument doc = new XWPFDocument(fis);

    for (XWPFParagraph p : doc.getParagraphs()) {

        for (XWPFRun r : p.getRuns()) {
            //System.out.println(r);
            String text = r.getText(0);

            System.out.println(text);
            if (text.contains("unidad")) {
                text = text.replace("unidad", "CICTE/W-6.a/02.00");

                r.setText(text, 0);/*from   w  w w .j  av  a2 s. com*/
                System.out.println(text);
            }

            if (text.contains("#receptor#")) {
                text = text.replace("#receptor#",
                        "Gral Brig Jefe del Servicio de Material de Guerra del Ejrcito");

                r.setText(text, 0);
                System.out.println(text);
            }

            if (text.contains("#asunto#")) {
                text = text.replace("#asunto#",
                        "Sobre artculo de MG (Armamento) y apoyo de elemento tcnico.");

                r.setText(text, 0);
                System.out.println(text);
            }

            if (text.contains("#referencia#")) {
                text = text.replace("#referencia#", "Oficio N289/CICTE del 01 julio de 2015.");

                r.setText(text, 0);
                System.out.println(text);
            }

            if (text.contains("#cuerpo#")) {
                text = text.replace("#cuerpo#",
                        "Tengo el honor de dirigirme a Ud., para manifestarle que en relacin a la solicitud de prstamo de una (01) ametralladora BROWNING Cal .50 y la participacin del elemento tcnico Tco 2da MAM Pacheco Tejada Henry, para las pruebas del vehculo blindado OTORONGO, las cuales se han suspendido y sern reprogramadas.\n"
                                + "Asimismo, se informar de manera oportuna la fecha de realizacin de las pruebas del vehculo blindado OTORONGO, para poder contar con artculo de MG (Armamento) y apoyo de elemento tcnico solicitado.\n"
                                + "Hago propicia la oportunidad para expresarle a Ud. los sentimientos de mi especial consideracin y estima personal.");

                r.setText(text, 0);
                System.out.println(text);
            }

        }

    }
    doc.write(new FileOutputStream("output.docx"));

}

From source file:myexamples.WordDocsExamples.Test1.java

public static void simplepartsReading() throws IOException {
    JFileChooser chooser = new JFileChooser();
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        System.out.println(chooser.getSelectedFile().getName());
        FileInputStream fis = new FileInputStream(chooser.getSelectedFile());
        XWPFDocument doc = new XWPFDocument(fis);
        XWPFWordExtractor extract = new XWPFWordExtractor(doc);
        //System.out.println(extract.getText());
        List<XWPFParagraph> pList = doc.getParagraphs();
        List<XWPFTable> tList = doc.getTables();

        System.out.println("Number of Paragraphs=" + pList.size());
        System.out.println("Number of Tables=" + tList.size());
        List<XWPFTableRow> rList;
        List<XWPFTableCell> cList;
        List<XWPFParagraph> rcpList;
        int tCount = 0, rCount = 0, cCount = 0, rcpCount = 0, dummCounter = 0;
        WordReference wordReference = new WordReference();
        for (XWPFTable t : tList) {
            rList = t.getRows();/* ww w  .  ja v a  2s.c  o  m*/
            rCount = 0;
            cCount = 0;
            rcpCount = 0;
            System.out.println("Table Nr." + (tCount++));
            for (XWPFTableRow r : rList) {
                cList = r.getTableCells();
                cCount = 0;
                rcpCount = 0;
                System.out.println("Row Nr." + (rCount++));
                for (XWPFTableCell c : cList) {
                    rcpList = c.getParagraphs();
                    rcpCount = 0;
                    System.out.println("Cell Nr." + (cCount++));
                    System.out.println("Cell Text: " + c.getText());
                    System.out.println("Nr of Tables: " + c.getTables().size());
                    for (XWPFParagraph rcp : rcpList) {
                        System.out.println("Par Nr." + (rcpCount++) + " Paragraphtext=" + rcp.getText());
                    }
                    for (XWPFTable t1 : c.getTables()) {
                        for (XWPFTableRow r1 : t1.getRows()) {
                            for (XWPFTableCell c1 : r1.getTableCells()) {
                                System.out.println("DC Nr." + dummCounter + " Cell Text: " + c1.getText());
                                switch (dummCounter) {
                                case 0:
                                    wordReference.kundenLogo = c1.getText();
                                    break;
                                case 1:
                                    wordReference.kundenprofil = c1.getText();
                                    break;
                                case 2:
                                    wordReference.ausgangslage = c1.getText();
                                    break;
                                case 3:
                                    wordReference.losung = c1.getText();
                                    break;
                                case 4:
                                    wordReference.ergebnis = c1.getText();
                                    break;
                                case 5:
                                    wordReference.kunde = c1.getText();
                                    break;
                                case 6:
                                    wordReference.projektname = c1.getText();
                                    break;
                                case 7:
                                    wordReference.kundenstatement = c1.getText();
                                    break;
                                case 8:
                                    wordReference.statementBei = c1.getText();
                                    break;
                                case 9:
                                    wordReference.flisstext = c1.getText();
                                    break;
                                default:
                                    ;
                                }
                                dummCounter++;
                            }
                        }

                    }
                }
            }
        }
        System.out.println(wordReference.toString(1));

    }
}

From source file:myexamples.WordDocsExamples.Test1.java

public static WordReference getWordReference() throws IOException {
    WordReference wordReference = new WordReference();
    JFileChooser chooser = new JFileChooser();
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        System.out.println(chooser.getSelectedFile().getName());
        FileInputStream fis = new FileInputStream(chooser.getSelectedFile());
        XWPFDocument doc = new XWPFDocument(fis);
        XWPFWordExtractor extract = new XWPFWordExtractor(doc);
        //System.out.println(extract.getText());
        List<XWPFParagraph> pList = doc.getParagraphs();
        List<XWPFTable> tList = doc.getTables();

        //            System.out.println("Number of Paragraphs="+pList.size());
        //            System.out.println("Number of Tables="+tList.size());
        List<XWPFTableRow> rList;
        List<XWPFTableCell> cList;
        List<XWPFParagraph> rcpList;
        int tCount = 0, rCount = 0, cCount = 0, rcpCount = 0, dummCounter = 0;

        for (XWPFTable t : tList) {
            rList = t.getRows();//w w w . j  av a 2 s  . c o m
            rCount = 0;
            cCount = 0;
            rcpCount = 0;
            //               System.out.println("Table Nr."+(tCount++));
            for (XWPFTableRow r : rList) {
                cList = r.getTableCells();
                cCount = 0;
                rcpCount = 0;
                //                System.out.println("Row Nr."+(rCount++));
                for (XWPFTableCell c : cList) {
                    rcpList = c.getParagraphs();
                    rcpCount = 0;
                    //                       System.out.println("Cell Nr."+(cCount++));
                    //                       System.out.println("Cell Text: "+c.getText());
                    //                       System.out.println("Nr of Tables: "+c.getTables().size());
                    for (XWPFParagraph rcp : rcpList) {
                        // System.out.println("Par Nr."+(rcpCount++)+" Paragraphtext="+ rcp.getText());
                    }
                    for (XWPFTable t1 : c.getTables()) {
                        for (XWPFTableRow r1 : t1.getRows()) {
                            for (XWPFTableCell c1 : r1.getTableCells()) {
                                //System.out.println("DC Nr."+dummCounter+" Cell Text: "+c1.getText());
                                switch (dummCounter) {
                                case 0:
                                    wordReference.kundenLogo = c1.getText();
                                    break;
                                case 1:
                                    wordReference.kundenprofil = c1.getText();
                                    break;
                                case 2:
                                    wordReference.ausgangslage = c1.getText();
                                    break;
                                case 3:
                                    wordReference.losung = c1.getText();
                                    break;
                                case 4:
                                    wordReference.ergebnis = c1.getText();
                                    break;
                                case 5:
                                    wordReference.kunde = c1.getText();
                                    break;
                                case 6:
                                    wordReference.projektname = c1.getText();
                                    break;
                                case 7:
                                    wordReference.kundenstatement = c1.getText();
                                    break;
                                case 8:
                                    wordReference.statementBei = c1.getText();
                                    break;
                                case 9:
                                    wordReference.flisstext = c1.getText();
                                    break;
                                default:
                                    ;
                                }
                                dummCounter++;
                            }
                        }

                    }
                }
            }
        }
        //System.out.println(wordReference.toString(1));

    }
    return wordReference;
}

From source file:offishell.word.Word.java

License:MIT License

/**
 * <p>//from ww  w.java2  s .  c o m
 * Replace variable text.
 * </p>
 * 
 * @param doc
 * @param object
 */
private void replace(XWPFDocument doc) {
    // for paragraph
    for (XWPFParagraph para : copy(doc.getParagraphs())) {
        replace(para);
    }

    // for table
    for (XWPFTable table : copy(doc.getTables())) {
        for (XWPFTableRow row : copy(table.getRows())) {
            for (XWPFTableCell cell : copy(row.getTableCells())) {
                for (XWPFParagraph para : copy(cell.getParagraphs())) {
                    replace(para);
                }
            }
        }
    }

    // for header
    for (XWPFHeader header : copy(doc.getHeaderList())) {
        for (XWPFParagraph para : copy(header.getParagraphs())) {
            replace(para);
        }
    }

    // for footer
    for (XWPFFooter footer : copy(doc.getFooterList())) {
        for (XWPFParagraph para : copy(footer.getParagraphs())) {
            replace(para);
        }
    }
}

From source file:offishell.word.WordHeleper.java

License:MIT License

/**
 * <p>/*from w ww  .j av a2 s  . c o m*/
 * Helper method to remove all comments from the specified document.
 * </p>
 * 
 * @param document A target document.
 */
public static void clearComment(XWPFDocument document) {
    for (XWPFParagraph paragraph : document.getParagraphs()) {
        clearComment(paragraph);
    }

    // for table
    for (XWPFTable table : document.getTables()) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                for (XWPFParagraph para : cell.getParagraphs()) {
                    clearComment(para);
                }
            }
        }
    }
}