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

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

Introduction

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

Prototype

@Override
public List<XWPFTable> getTables() 

Source Link

Usage

From source file:edu.gatech.pmase.capstone.awesome.impl.output.DisasterResponseTradeStudyOutputer.java

License:Open Source License

@Override
public Path createOutputFile(final List<DRTSArchitectureResult> results,
        final List<DisasterEffect> selectedDisasterEffects, final List<TerrainEffect> selectedTerrainEffects)
        throws IOException, InvalidFormatException {
    // set time/*  w w w  .j a  v a2 s.c om*/
    now = ZonedDateTime.now();

    LOGGER.info("Creating results architecture file.");
    final String filename = "DRTS-Results-" + fileNameFormatter.format(now) + ".docx";

    // create paths
    final Path templatePath = Paths.get(
            DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory(),
            DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsTemplate());

    final Path resultsDir = Paths
            .get(DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory());

    Path resultPath = Paths
            .get(DisasterResponseTradeStudyPropertiesSingleton.getInstance().getResultsDirectory(), filename);

    // copy template file
    final File workbookFile = templatePath.toFile();

    if (workbookFile.exists() && !workbookFile.isDirectory() && workbookFile.canRead()) {
        LOGGER.debug("Using results template file: " + workbookFile.getAbsolutePath());
        final XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(workbookFile));

        // get table
        final List<XWPFTable> tables = xdoc.getTables();

        // set values
        DRTSArchitectureResult result = null;

        if (null != results && !results.isEmpty()) {
            result = results.get(0);

            // create platform weightings table
            this.createOptionWeightingTable(result.getPlatform(), tables.get(PLATFORM_WEIGHTING_TABLE_INDEX));

            // create comm weighting table
            this.createOptionWeightingTable(result.getComms(), tables.get(COMM_WEIGHTING_TABLE_INDEX));

            // create sensor weighting table
            this.createOptionWeightingTable(result.getSensor(), tables.get(SENSOR_WEIGHTING_TABLE_INDEX));
        } else {
            LOGGER.warn("No architecture result found, cannot place into output result.");
        }

        // create arch table
        this.createArchTable(result, tables.get(ARCH_RESULT_TABLE_INDEX));

        // create disaster effect table
        this.createSelectedDisasterTable(selectedDisasterEffects, tables.get(SELECTED_DISASTER_TABLE_INDEX));

        // create selected terrain table
        this.createSelectedTerrainTable(selectedTerrainEffects, tables.get(SELECTED_TERRAIN_TABLE_INDEX));

        // create details
        this.createReportDetails(xdoc);

        // get result file
        final File resultFile = resultPath.toFile();
        LOGGER.debug("Trying to use result file: " + resultFile.getAbsolutePath());
        LOGGER.debug("Result file is in result directory: " + resultsDir.toAbsolutePath());

        if (!resultFile.isDirectory() && Files.isDirectory(resultsDir) && Files.isWritable(resultsDir)) {
            LOGGER.debug("Creating result file: " + resultFile.getAbsolutePath());
            // write out result
            try (final FileOutputStream outStream = new FileOutputStream(resultFile)) {
                xdoc.write(outStream);
            }
        } else {
            LOGGER.error("Cannot create output result file at path: " + resultFile.getAbsolutePath());
            resultPath = null;
        }
    } else {
        LOGGER.error("Cannot read input workbook file at path: " + templatePath.toString());
        resultPath = null;
    }

    return resultPath;
}

From source file:javaapplication1.AnotherPOI.java

public static void replaceText(String findText, String replaceText) {
    try {//from  w  w w .j a  v a 2 s .  co m
        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 ww . j a  va2s.  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: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();//from w  w w  .  j ava 2s.  co  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();/*from   www .  ja  v 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>/*  w w  w . ja va 2  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 w  w. ja  va  2 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);
                }
            }
        }
    }
}

From source file:org.kino.server.api.contractgenerator.java

static void writeDocxTemplate(InputStream src, OutputStream dststrem, Map<String, String> replacementMap)
        throws InvalidFormatException, IOException {
    XWPFDocument doc = new XWPFDocument(src);
    replaceInParagraphs(replacementMap, doc.getParagraphs());
    for (XWPFTable tbl : doc.getTables()) {
        for (XWPFTableRow row : tbl.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                replaceInParagraphs(replacementMap, cell.getParagraphs());

            }//from   w  w w  . j ava 2 s .c  o  m
        }
    }

    doc.write(dststrem);

}