Java Examples for org.apache.poi.xwpf.usermodel.XWPFTableRow

The following java examples will help you to understand the usage of org.apache.poi.xwpf.usermodel.XWPFTableRow. These source code samples are taken from different open source projects.

Example 1
Project: poi-tl-master  File: TemplateResolver.java View source code
public static List<ElementTemplate> parseTable(XWPFTable table) {
    if (null == table)
        return null;
    List<ElementTemplate> rts = new ArrayList<ElementTemplate>();
    List<XWPFTableRow> rows = table.getRows();
    if (null != rows) {
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            if (null != cells) {
                for (XWPFTableCell cell : cells) {
                    // cell暂时无法方便的实现文字和样式修改
                    // CellTemplate parseCell = parseCell(cell);
                    // if (null != parseCell) {
                    // rts.add(parseCell);
                    // } else {
                    rts.addAll(parseParagraph(cell.getParagraphs()));
                    rts.addAll(parseTable(cell.getTables()));
                }
            }
        }
    }
    return rts;
}
Example 2
Project: Aspose_Words_for_Apache_POI-master  File: ApacheFormattedTable.java View source code
public static void main(String[] args) throws Exception {
    String dataPath = "src/featurescomparison/workingwithtables/formattable/data/";
    // Create a new document from scratch
    XWPFDocument doc = new XWPFDocument();
    // -- OR --
    // open an existing empty document with styles already defined
    //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
    // Create a new table with 6 rows and 3 columns
    int nRows = 6;
    int nCols = 3;
    XWPFTable table = doc.createTable(nRows, nCols);
    // Set the table style. If the style is not defined, the table style
    // will become "Normal".
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTString styleStr = tblPr.addNewTblStyle();
    styleStr.setVal("StyledTable");
    // Get a list of the rows in the table
    List<XWPFTableRow> rows = table.getRows();
    int rowCt = 0;
    int colCt = 0;
    for (XWPFTableRow row : rows) {
        // get table row properties (trPr)
        CTTrPr trPr = row.getCtRow().addNewTrPr();
        // set row height; units = twentieth of a point, 360 = 0.25"
        CTHeight ht = trPr.addNewTrHeight();
        ht.setVal(BigInteger.valueOf(360));
        // get the cells in this row
        List<XWPFTableCell> cells = row.getTableCells();
        // add content to each cell
        for (XWPFTableCell cell : cells) {
            // get a table cell properties element (tcPr)
            CTTcPr tcpr = cell.getCTTc().addNewTcPr();
            // set vertical alignment to "center"
            CTVerticalJc va = tcpr.addNewVAlign();
            va.setVal(STVerticalJc.CENTER);
            // create cell color element
            CTShd ctshd = tcpr.addNewShd();
            ctshd.setColor("auto");
            ctshd.setVal(STShd.CLEAR);
            if (rowCt == 0) {
                // header row
                ctshd.setFill("A7BFDE");
            } else if (rowCt % 2 == 0) {
                // even row
                ctshd.setFill("D3DFEE");
            } else {
                // odd row
                ctshd.setFill("EDF2F8");
            }
            // get 1st paragraph in cell's paragraph list
            XWPFParagraph para = cell.getParagraphs().get(0);
            // create a run to contain the content
            XWPFRun rh = para.createRun();
            // style cell as desired
            if (colCt == nCols - 1) {
                // last column is 10pt Courier
                rh.setFontSize(10);
                rh.setFontFamily("Courier");
            }
            if (rowCt == 0) {
                // header row
                rh.setText("header row, col " + colCt);
                rh.setBold(true);
                para.setAlignment(ParagraphAlignment.CENTER);
            } else if (rowCt % 2 == 0) {
                // even row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            } else {
                // odd row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            }
            colCt++;
        }
        // for cell
        colCt = 0;
        rowCt++;
    }
    // for row
    // write the file
    FileOutputStream out = new FileOutputStream(dataPath + "Apache_styledTable_Out.docx");
    doc.write(out);
    out.close();
    System.out.println("Process Completed Successfully");
}
Example 3
Project: xdocreport-master  File: XWPFTableUtil.java View source code
/**
     * Compute column widths of the XWPF table.
     * 
     * @param table
     * @return
     */
public static float[] computeColWidths(XWPFTable table) {
    XWPFTableRow firstRow = getFirstRow(table);
    float[] colWidths;
    // Get first row to know if there is cell which have gridSpan to compute
    // columns number.
    int nbCols = getNumberOfColumns(firstRow);
    // Compare nbCols computed with number of grid colList
    CTTblGrid grid = table.getCTTbl().getTblGrid();
    List<CTTblGridCol> cols = getGridColList(grid);
    if (nbCols > cols.size()) {
        Collection<Float> maxColWidths = null;
        Collection<Float> currentColWidths = null;
        // nbCols computed is not equals to number of grid colList
        // columns width must be computed by looping for each row/cells
        List<XWPFTableRow> rows = table.getRows();
        for (XWPFTableRow row : rows) {
            currentColWidths = computeColWidths(row);
            if (maxColWidths == null) {
                maxColWidths = currentColWidths;
            } else {
                if (currentColWidths.size() > maxColWidths.size()) {
                    maxColWidths = currentColWidths;
                }
            }
        }
        colWidths = new float[maxColWidths.size()];
        int i = 0;
        for (Float colWidth : maxColWidths) {
            colWidths[i++] = colWidth;
        }
        return colWidths;
    } else {
        // If w:gridAfter is defined, ignore the last columns defined on the gridColumn
        int nbColumnsToIgnoreBefore = getNbColumnsToIgnore(firstRow, true);
        int nbColumnsToIgnoreAfter = getNbColumnsToIgnore(firstRow, false);
        int nbColumns = cols.size() - nbColumnsToIgnoreBefore - nbColumnsToIgnoreAfter;
        // nbCols computed is equals to number of grid colList
        // columns width can be computed by using the grid colList
        colWidths = new float[nbColumns];
        float colWidth = -1;
        for (int i = nbColumnsToIgnoreBefore; i < colWidths.length; i++) {
            CTTblGridCol tblGridCol = cols.get(i);
            colWidth = tblGridCol.getW().floatValue();
            colWidths[i] = dxa2points(colWidth);
        }
    }
    return colWidths;
}
Example 4
Project: poi-master  File: SimpleTable.java View source code
/**
     * Create a table with some row and column styling. I "manually" add the
     * style name to the table, but don't check to see if the style actually
     * exists in the document. Since I'm creating it from scratch, it obviously
     * won't exist. When opened in MS Word, the table style becomes "Normal".
     * I manually set alternating row colors. This could be done using Themes,
     * but that's left as an exercise for the reader. The cells in the last
     * column of the table have 10pt. "Courier" font.
     * I make no claims that this is the "right" way to do it, but it worked
     * for me. Given the scarcity of XWPF examples, I thought this may prove
     * instructive and give you ideas for your own solutions.

     * @throws Exception
     */
public static void createStyledTable() throws Exception {
    // Create a new document from scratch
    XWPFDocument doc = new XWPFDocument();
    try {
        // -- OR --
        // open an existing empty document with styles already defined
        //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
        // Create a new table with 6 rows and 3 columns
        int nRows = 6;
        int nCols = 3;
        XWPFTable table = doc.createTable(nRows, nCols);
        // Set the table style. If the style is not defined, the table style
        // will become "Normal".
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        CTString styleStr = tblPr.addNewTblStyle();
        styleStr.setVal("StyledTable");
        // Get a list of the rows in the table
        List<XWPFTableRow> rows = table.getRows();
        int rowCt = 0;
        int colCt = 0;
        for (XWPFTableRow row : rows) {
            // get table row properties (trPr)
            CTTrPr trPr = row.getCtRow().addNewTrPr();
            // set row height; units = twentieth of a point, 360 = 0.25"
            CTHeight ht = trPr.addNewTrHeight();
            ht.setVal(BigInteger.valueOf(360));
            // get the cells in this row
            List<XWPFTableCell> cells = row.getTableCells();
            // add content to each cell
            for (XWPFTableCell cell : cells) {
                // get a table cell properties element (tcPr)
                CTTcPr tcpr = cell.getCTTc().addNewTcPr();
                // set vertical alignment to "center"
                CTVerticalJc va = tcpr.addNewVAlign();
                va.setVal(STVerticalJc.CENTER);
                // create cell color element
                CTShd ctshd = tcpr.addNewShd();
                ctshd.setColor("auto");
                ctshd.setVal(STShd.CLEAR);
                if (rowCt == 0) {
                    // header row
                    ctshd.setFill("A7BFDE");
                } else if (rowCt % 2 == 0) {
                    // even row
                    ctshd.setFill("D3DFEE");
                } else {
                    // odd row
                    ctshd.setFill("EDF2F8");
                }
                // get 1st paragraph in cell's paragraph list
                XWPFParagraph para = cell.getParagraphs().get(0);
                // create a run to contain the content
                XWPFRun rh = para.createRun();
                // style cell as desired
                if (colCt == nCols - 1) {
                    // last column is 10pt Courier
                    rh.setFontSize(10);
                    rh.setFontFamily("Courier");
                }
                if (rowCt == 0) {
                    // header row
                    rh.setText("header row, col " + colCt);
                    rh.setBold(true);
                    para.setAlignment(ParagraphAlignment.CENTER);
                } else {
                    // other rows
                    rh.setText("row " + rowCt + ", col " + colCt);
                    para.setAlignment(ParagraphAlignment.LEFT);
                }
                colCt++;
            }
            // for cell
            colCt = 0;
            rowCt++;
        }
        // for row
        // write the file
        OutputStream out = new FileOutputStream("styledTable.docx");
        try {
            doc.write(out);
        } finally {
            out.close();
        }
    } finally {
        doc.close();
    }
}
Example 5
Project: WhiteRabbit-master  File: ETLDocumentGenerator.java View source code
private static void addSourceTablesAppendix(CustomXWPFDocument document, ETL etl) {
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    run.addBreak(BreakType.PAGE);
    run.setText("Appendix: source tables");
    run.setFontSize(18);
    for (Table sourceTable : etl.getSourceDatabase().getTables()) {
        paragraph = document.createParagraph();
        run = paragraph.createRun();
        run.setText("Table: " + sourceTable.getName());
        run.setFontSize(14);
        createDocumentParagraph(document, sourceTable.getComment());
        XWPFTable table = document.createTable(sourceTable.getFields().size() + 1, 4);
        // table.setWidth(2000);
        XWPFTableRow header = table.getRow(0);
        setTextAndHeaderShading(header.getCell(0), "Field");
        setTextAndHeaderShading(header.getCell(1), "Type");
        setTextAndHeaderShading(header.getCell(2), "Most freq. value");
        setTextAndHeaderShading(header.getCell(3), "Comment");
        int rowNr = 1;
        for (Field sourceField : sourceTable.getFields()) {
            XWPFTableRow row = table.getRow(rowNr++);
            row.getCell(0).setText(sourceField.getName());
            row.getCell(1).setText(sourceField.getType());
            if (sourceField.getValueCounts() != null && sourceField.getValueCounts().length != 0)
                row.getCell(2).setText(sourceField.getValueCounts()[0][0]);
            createCellParagraph(row.getCell(3), sourceField.getComment().trim());
        }
    }
    run.setFontSize(18);
}
Example 6
Project: DBDocTool-master  File: Word2007.java View source code
/**
     * 生成word,表格
     * 
     * @param data
     * @throws Exception
     */
public static void productWordForm(Map<String, String> tableinfo, Map<String, LinkedHashMap<String, LinkedHashMap<String, String>>> data, Parameters parameters) throws Exception {
    XWPFDocument xDocument = new XWPFDocument();
    Iterator<String> tableNameIter = data.keySet().iterator();
    while (tableNameIter.hasNext()) {
        String table_name = tableNameIter.next();
        XWPFParagraph xp = xDocument.createParagraph();
        XWPFRun r1 = xp.createRun();
        r1.setText(table_name + " " + tableinfo.get(table_name));
        r1.setFontSize(18);
        r1.setTextPosition(10);
        XWPFParagraph p = xDocument.createParagraph();
        p.setAlignment(ParagraphAlignment.CENTER);
        p.setWordWrap(true);
        LinkedHashMap<String, LinkedHashMap<String, String>> columns = data.get(table_name);
        int rows = columns.size();
        XWPFTable xTable = xDocument.createTable(rows + 1, 7);
        //表格属性
        CTTblPr tablePr = xTable.getCTTbl().addNewTblPr();
        //表格宽度
        CTTblWidth width = tablePr.addNewTblW();
        width.setW(BigInteger.valueOf(8600));
        int i = 0;
        xTable.getRow(i).setHeight(380);
        setCellText(xDocument, xTable.getRow(i).getCell(0), "代码", "CCCCCC", getCellWidth(0));
        setCellText(xDocument, xTable.getRow(i).getCell(1), "注释", "CCCCCC", getCellWidth(1));
        setCellText(xDocument, xTable.getRow(i).getCell(2), "类型", "CCCCCC", getCellWidth(2));
        setCellText(xDocument, xTable.getRow(i).getCell(3), "默认值", "CCCCCC", getCellWidth(3));
        setCellText(xDocument, xTable.getRow(i).getCell(4), "标识", "CCCCCC", getCellWidth(4));
        setCellText(xDocument, xTable.getRow(i).getCell(5), "主键", "CCCCCC", getCellWidth(5));
        setCellText(xDocument, xTable.getRow(i).getCell(6), "空值", "CCCCCC", getCellWidth(6));
        // 下一行
        i = i + 1;
        // 列column索引
        int j = 0;
        Map<String, LinkedHashMap<String, String>> keyColumnMap = keyColumns(columns);
        for (Iterator<String> columnNameIter = keyColumnMap.keySet().iterator(); columnNameIter.hasNext(); ) {
            String column_name = columnNameIter.next();
            LinkedHashMap<String, String> columnsAtt = keyColumnMap.get(column_name);
            int cwidth = getCellWidth(j);
            setCellText(xDocument, xTable.getRow(i).getCell(j), column_name, "FFFFFF", cwidth);
            ++j;
            Iterator<String> columnTypeIter = columnsAtt.keySet().iterator();
            while (columnTypeIter.hasNext()) {
                String colum_type = columnTypeIter.next();
                cwidth = getCellWidth(j);
                setCellText(xDocument, xTable.getRow(i).getCell(j), columnsAtt.get(colum_type), "FFFFFF", cwidth);
                j++;
            }
            // 下一行
            ++i;
            // 恢复第一列
            j = 0;
        }
        Iterator<String> cloumnsNameIter = columns.keySet().iterator();
        while (cloumnsNameIter.hasNext()) {
            xTable.getRow(i).setHeight(380);
            String colum_name = cloumnsNameIter.next();
            LinkedHashMap<String, String> columnsAtt = columns.get(colum_name);
            int cwidth = getCellWidth(j);
            if (xTable.getRow(i) == null)
                continue;
            setCellText(xDocument, xTable.getRow(i).getCell(j), colum_name, "FFFFFF", cwidth);
            j++;
            Iterator<String> columnTypeIter = columnsAtt.keySet().iterator();
            while (columnTypeIter.hasNext()) {
                String colum_type = columnTypeIter.next();
                cwidth = getCellWidth(j);
                setCellText(xDocument, xTable.getRow(i).getCell(j), columnsAtt.get(colum_type), "FFFFFF", cwidth);
                j++;
            }
            // 恢复第一列
            j = 0;
            //下一行
            ++i;
        }
        XWPFTableRow row = xTable.insertNewTableRow(0);
        row.setHeight(380);
        row.addNewTableCell();
        CTTcPr cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(1600));
        row.getCell(0).setColor("CCCCCC");
        row.getCell(0).setText("中文名称");
        row.addNewTableCell();
        cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(3000));
        row.getCell(1).setColor("FFFFFF");
        row.getCell(1).setText(tableinfo.get(table_name));
        row.addNewTableCell();
        cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(1200));
        row.getCell(2).setColor("CCCCCC");
        row.getCell(2).setText("英文名称");
        row.addNewTableCell();
        CTTc cttc = row.getCell(3).getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(2800));
        ctPr.addNewGridSpan().setVal(BigInteger.valueOf(4));
        ctPr.addNewHMerge().setVal(STMerge.CONTINUE);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
        cttc.getPList().get(0).addNewR().addNewT().setStringValue(table_name);
        row = xTable.insertNewTableRow(1);
        row.setHeight(380);
        row.addNewTableCell();
        cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(1600));
        row.getCell(0).setColor("CCCCCC");
        row.getCell(0).setText("功能描述");
        row.addNewTableCell();
        cellPr = row.getCell(0).getCTTc().addNewTcPr();
        cellPr.addNewTcW().setW(BigInteger.valueOf(7000));
        cttc = row.getCell(1).getCTTc();
        ctPr = cttc.addNewTcPr();
        ctPr.addNewGridSpan().setVal(BigInteger.valueOf(6));
        ctPr.addNewHMerge().setVal(STMerge.CONTINUE);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.LEFT);
        cttc.getPList().get(0).addNewR().addNewT().setStringValue("");
    }
    FileOutputStream fos = new FileOutputStream(parameters.getPath() + parameters.getDatabase() + "_doc.docx");
    xDocument.write(fos);
    fos.close();
}
Example 7
Project: minos-master  File: PrintResult.java View source code
public void print(int actorsID, String outputFileName, String sinnerFIO) {
    double commonResult = 0.0;
    String sql = " select mc.name, mc.variety, mrp.cost, mp.min_level from MinosRoundProfile mrp " + " inner join MinosProfile mp on mp.id = mrp.profile_id " + " inner join MinosRoundActors mra on mra.id = mrp.actors_id " + " inner join MinosRound mr on mr.id = mra.round_id " + " inner join MinosCompetence mc on mc.incarnatio = mp.competence_incarnatio " + " where mr.round_start between mc.date_create and mc.date_remove " + " and mrp.actors_id = %id% " + " order by mc.variety";
    String request = kdb.makeSQLString(sql, "%id%", String.valueOf(actorsID));
    Preconditions.checkNotNull(request, "PrintResult.print() : makeListParam() return null");
    TableKeeper tk = null;
    try {
        tk = kdb.selectRows(request);
        if ((tk == null) || (tk.getRowCount() == 0))
            return;
        int profileSum = 0;
        double resultSum = 0.0;
        for (int i = 0; i < tk.getRowCount(); i++) {
            profileSum += (Integer) tk.getValue(i + 1, 4);
            resultSum += (Double) tk.getValue(i + 1, 3);
        }
        commonResult = resultSum * 100 / profileSum;
        // open and save pattern file
        XWPFDocument patternDoc = new XWPFDocument(new FileInputStream(patternWordFile));
        patternDoc.write(new FileOutputStream(outputFileName));
        XWPFDocument workDoc = new XWPFDocument(new FileInputStream(outputFileName));
        List<XWPFTable> tbls = workDoc.getTables();
        List<XWPFTableRow> rows = tbls.get(0).getRows();
        int competenceNum = 1;
        boolean fCompetenceWrite = false;
        boolean fProfileWrite = false;
        String profileColor = null;
        boolean fResultWrite = false;
        String resultColor = null;
        int counter;
        boolean flagCompetenceListFinish = false;
        int rowForDeleteStart = -1;
        int rowForDeleteStop = -1;
        System.out.println(rows.size());
        for (int i = 0; i < rows.size(); i++) {
            // ��������� ������������� ������ � �������� ��� ������ ����������
            int num = findCompetenceTestResult(rows.get(i), TEST_RESULT_PATTERN);
            if (num >= 0) {
                clearParagraphsAndRuns(rows.get(i).getCell(num));
                rows.get(i).getCell(num).getParagraphs().get(0).getRuns().get(0).setText(String.format("%4.1f", commonResult) + " %", 0);
                continue;
            }
            // ��������� ������������� ������ � �������� ��� ������ ����������
            num = findCompetenceTestResult(rows.get(i), SINNNER_FIO_PATTERN);
            if (num >= 0) {
                clearParagraphsAndRuns(rows.get(i).getCell(num));
                rows.get(i).getCell(num).getParagraphs().get(0).getRuns().get(0).setText(sinnerFIO, 0);
                continue;
            }
            // ������� ������ ������
            if (flagCompetenceListFinish) {
                rowForDeleteStart = (rowForDeleteStart < 0 ? i : rowForDeleteStart);
                rowForDeleteStop = i;
            }
            resultColor = profileColor = null;
            counter = 0;
            List<XWPFTableCell> cells = rows.get(i).getTableCells();
            for (int j = 0; j < cells.size(); j++) {
                if (cells.get(j).getText().equalsIgnoreCase(COMPETENCE_PATTERN) && !flagCompetenceListFinish) {
                    clearParagraphsAndRuns(cells.get(j));
                    cells.get(j).getParagraphs().get(0).getRuns().get(0).setText((String) tk.getValue(competenceNum, 1), 0);
                    fCompetenceWrite = true;
                    continue;
                }
                if (cells.get(j).getText().equalsIgnoreCase("profile_level") && !flagCompetenceListFinish) {
                    clearParagraphsAndRuns(cells.get(j));
                    XWPFRun run = cells.get(j).getParagraphs().get(0).getRuns().get(0);
                    run.setText(" ", 0);
                    profileColor = run.getColor();
                    counter = 1;
                    fProfileWrite = true;
                    if (counter > (Integer) tk.getValue(competenceNum, 4))
                        break;
                }
                if (profileColor != null) {
                    if (counter <= ((Integer) tk.getValue(competenceNum, 4))) {
                        cells.get(j).setColor(profileColor);
                        counter++;
                        continue;
                    }
                    break;
                }
                if (cells.get(j).getText().equalsIgnoreCase("Result_level") && !flagCompetenceListFinish) {
                    clearParagraphsAndRuns(cells.get(j));
                    XWPFRun run = cells.get(j).getParagraphs().get(0).getRuns().get(0);
                    run.setText(" ", 0);
                    resultColor = run.getColor();
                    counter = 1;
                    fResultWrite = true;
                    Double d = (Double) tk.getValue(competenceNum, 3);
                    if (counter > d.intValue())
                        break;
                }
                if (resultColor != null) {
                    Double d = (Double) tk.getValue(competenceNum, 3);
                    if (counter <= d.intValue()) {
                        cells.get(j).setColor(resultColor);
                        counter++;
                        continue;
                    }
                    break;
                }
            }
            if (fCompetenceWrite && fProfileWrite && fResultWrite) {
                fCompetenceWrite = fResultWrite = fProfileWrite = false;
                competenceNum++;
                if (competenceNum > tk.getRowCount())
                    flagCompetenceListFinish = true;
            }
        }
        //remove superfluous rows
        int diff = rowForDeleteStop - rowForDeleteStart + 1;
        for (int i = 0; i < diff; i++) tbls.get(0).removeRow(rowForDeleteStart);
        workDoc.write(new FileOutputStream(outputFileName));
    } catch (Exception e) {
        e.printStackTrace();
        tk = null;
    }
}
Example 8
Project: OCRaptor-master  File: XWPFWordExtractorDecorator.java View source code
private void extractTable(XWPFTable table, XHTMLContentHandler xhtml) throws SAXException, XmlException, IOException {
    xhtml.startElement("table");
    xhtml.startElement("tbody");
    for (XWPFTableRow row : table.getRows()) {
        xhtml.startElement("tr");
        for (XWPFTableCell cell : row.getTableCells()) {
            xhtml.startElement("td");
            extractIBodyText(cell, xhtml);
            xhtml.endElement("td");
        }
        xhtml.endElement("tr");
    }
    xhtml.endElement("tbody");
    xhtml.endElement("table");
}
Example 9
Project: HazardTrackingSystem-master  File: HazardReportGenerator.java View source code
// private void createFooter(XWPFDocument doc, Hazards h) throws
// IOException, XmlException {
// //
// http://stackoverflow.com/questions/16442347/counting-pages-in-a-word-document
//
// XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
// headerFooterPolicy.createFooter(STHdrFtr.DEFAULT);
// XWPFFooter footer = headerFooterPolicy.getDefaultFooter();
// // new ParagraphBuilder().text("test").createFooterText(footer);
// XmlDocumentProperties documentProperties =
// doc.getDocument().documentProperties();
//
// doc.createNumbering();
// }
/**
	 * Adds the header section of NF1825 to the document. The header section
	 * contains hazard number, phases affected, author, etc.
	 * 
	 * @param doc
	 *            the template document that hazard data is being added to
	 * @param h
	 *            the hazard that is currently being written to the document
	 * @param reviewPhases
	 *            a list of ALL possible Review Phases in the system. This is
	 *            NOT the review phase for the hazard.
	 */
private void createHeader(XWPFDocument doc, Hazards h, List<Review_Phases> reviewPhases) {
    // Remove the default paragraph in Template.docx
    doc.removeBodyElement(0);
    XWPFTable top = new TableBuilder().size(1, 2).createTable(doc);
    XWPFTableRow row;
    XWPFTableCell cell;
    row = top.getRow(0);
    // "Payload Hazard Report"
    cell = row.getCell(0);
    cell.setVerticalAlignment(XWPFVertAlign.CENTER);
    setColSpan(cell, 3);
    new ParagraphBuilder().text("NASA Expendable Launch Vehicle (ELV)").bold(true).fontSize(14).createCellText(cell);
    new ParagraphBuilder().text("Payload Safety Hazard Report").bold(true).fontSize(14).createCellText(cell);
    new ParagraphBuilder().text("(NPR 8715.7 and NASA-STD 8719.24)").fontSize(8).createCellText(cell);
    // Hazard report number and initiation date.
    // Can't do row spans, so these "two" cells in the Payload Form are
    // actually one cell with a paragraph border.
    cell = row.getCell(1);
    new CellHeaderBuilder().text("1. Hazard Report #:").createCellHeader(cell);
    new ParagraphBuilder().text(h.getHazardNumber()).bold(true).fontSize(10).leftMargin(0).alignment(ParagraphAlignment.CENTER).bottomBorder().createCellText(cell);
    new CellHeaderBuilder().text("2. Initiation Date: ").createCellHeader(cell);
    String date = h.getInitiationDate() != null ? df.format(h.getInitiationDate()) : "";
    new ParagraphBuilder().text(date).createCellText(cell);
    // --------------------------------------
    row = new TableBuilder().size(1, 2).createTable(doc).getRow(0);
    // Payload and Payload Safety Engineer
    cell = row.getCell(0);
    cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(5000));
    setColSpan(cell, 3);
    new CellHeaderBuilder().text("3. Project Name:").createCellHeader(cell);
    Project projectObj = projectManager.getProjectObj(h.getProjectID());
    String hProjectName = projectObj == null ? "" : projectObj.getName();
    new ParagraphBuilder().text(hProjectName).bottomBorder().createCellText(cell);
    new CellHeaderBuilder().text("Payload System Safety Engineer:").createCellHeader(cell);
    new ParagraphBuilder().text(h.getPreparer()).createCellText(cell);
    // Review Phase
    cell = row.getCell(1);
    new CellHeaderBuilder().text("4. Review Phase: ").createCellHeader(cell);
    for (Review_Phases phase : reviewPhases) {
        if (h.getReviewPhase() != null) {
            if (phase.getID() == h.getReviewPhase().getID())
                new ParagraphBuilder().text("☒\t\t" + phase.getLabel()).leftMargin(100).createCellText(cell);
            else
                new ParagraphBuilder().text("☐\t\t" + phase.getLabel()).leftMargin(100).createCellText(cell);
        }
    }
    // --------------------------------------
    row = new TableBuilder().size(1, 3).createTable(doc).getRow(0);
    // Subsystems
    cell = row.getCell(0);
    setColSpan(cell, 2);
    new CellHeaderBuilder().text("5. System/Subsystem: ").createCellHeader(cell);
    for (Subsystems s : h.getSubsystems()) {
        new ParagraphBuilder().text(s.getLabel()).createCellText(cell);
    }
    // Hazard groups
    cell = row.getCell(1);
    new CellHeaderBuilder().text("6. Hazard Group(s): ").createCellHeader(cell);
    for (Hazard_Group g : h.getHazardGroups()) {
        new ParagraphBuilder().text(g.getLabel()).createCellText(cell);
    }
    // Date
    cell = row.getCell(2);
    new CellHeaderBuilder().text("7. Date: ").createCellHeader(cell);
    String revisionDate = h.getRevisionDate() != null ? df.format(h.getRevisionDate()) : "";
    new ParagraphBuilder().text(revisionDate).createCellText(cell);
    // --------------------------------------
    row = new TableBuilder().size(1, 1).createTable(doc).getRow(0);
    // TODO: Applicable Safety Requirements
    cell = row.getCell(0);
    setColSpan(cell, 4);
    new CellHeaderBuilder().text("8. Applicable Safety Requirements: ").createCellHeader(cell);
    new ParagraphBuilder().text("N/A").createCellText(cell);
}
Example 10
Project: Aspose_Words_Java-master  File: ApacheFormattedTable.java View source code
public static void main(String[] args) throws Exception {
    // The path to the documents directory.
    String dataDir = Utils.getDataDir(ApacheFormattedTable.class);
    // Create a new document from scratch
    XWPFDocument doc = new XWPFDocument();
    // -- OR --
    // open an existing empty document with styles already defined
    //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
    // Create a new table with 6 rows and 3 columns
    int nRows = 6;
    int nCols = 3;
    XWPFTable table = doc.createTable(nRows, nCols);
    // Set the table style. If the style is not defined, the table style
    // will become "Normal".
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTString styleStr = tblPr.addNewTblStyle();
    styleStr.setVal("StyledTable");
    // Get a list of the rows in the table
    List<XWPFTableRow> rows = table.getRows();
    int rowCt = 0;
    int colCt = 0;
    for (XWPFTableRow row : rows) {
        // get table row properties (trPr)
        CTTrPr trPr = row.getCtRow().addNewTrPr();
        // set row height; units = twentieth of a point, 360 = 0.25"
        CTHeight ht = trPr.addNewTrHeight();
        ht.setVal(BigInteger.valueOf(360));
        // get the cells in this row
        List<XWPFTableCell> cells = row.getTableCells();
        // add content to each cell
        for (XWPFTableCell cell : cells) {
            // get a table cell properties element (tcPr)
            CTTcPr tcpr = cell.getCTTc().addNewTcPr();
            // set vertical alignment to "center"
            CTVerticalJc va = tcpr.addNewVAlign();
            va.setVal(STVerticalJc.CENTER);
            // create cell color element
            CTShd ctshd = tcpr.addNewShd();
            ctshd.setColor("auto");
            ctshd.setVal(STShd.CLEAR);
            if (rowCt == 0) {
                // header row
                ctshd.setFill("A7BFDE");
            } else if (rowCt % 2 == 0) {
                // even row
                ctshd.setFill("D3DFEE");
            } else {
                // odd row
                ctshd.setFill("EDF2F8");
            }
            // get 1st paragraph in cell's paragraph list
            XWPFParagraph para = cell.getParagraphs().get(0);
            // create a run to contain the content
            XWPFRun rh = para.createRun();
            // style cell as desired
            if (colCt == nCols - 1) {
                // last column is 10pt Courier
                rh.setFontSize(10);
                rh.setFontFamily("Courier");
            }
            if (rowCt == 0) {
                // header row
                rh.setText("header row, col " + colCt);
                rh.setBold(true);
                para.setAlignment(ParagraphAlignment.CENTER);
            } else if (rowCt % 2 == 0) {
                // even row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            } else {
                // odd row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            }
            colCt++;
        }
        // for cell
        colCt = 0;
        rowCt++;
    }
    // for row
    // write the file
    FileOutputStream out = new FileOutputStream(dataDir + "Apache_styledTable.docx");
    doc.write(out);
    out.close();
    System.out.println("Process Completed Successfully");
}
Example 11
Project: Aspose_for_Apache_POI-master  File: ApacheFormattedTable.java View source code
public static void main(String[] args) throws Exception {
    // Create a new document from scratch
    XWPFDocument doc = new XWPFDocument();
    // -- OR --
    // open an existing empty document with styles already defined
    //XWPFDocument doc = new XWPFDocument(new FileInputStream("base_document.docx"));
    // Create a new table with 6 rows and 3 columns
    int nRows = 6;
    int nCols = 3;
    XWPFTable table = doc.createTable(nRows, nCols);
    // Set the table style. If the style is not defined, the table style
    // will become "Normal".
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTString styleStr = tblPr.addNewTblStyle();
    styleStr.setVal("StyledTable");
    // Get a list of the rows in the table
    List<XWPFTableRow> rows = table.getRows();
    int rowCt = 0;
    int colCt = 0;
    for (XWPFTableRow row : rows) {
        // get table row properties (trPr)
        CTTrPr trPr = row.getCtRow().addNewTrPr();
        // set row height; units = twentieth of a point, 360 = 0.25"
        CTHeight ht = trPr.addNewTrHeight();
        ht.setVal(BigInteger.valueOf(360));
        // get the cells in this row
        List<XWPFTableCell> cells = row.getTableCells();
        // add content to each cell
        for (XWPFTableCell cell : cells) {
            // get a table cell properties element (tcPr)
            CTTcPr tcpr = cell.getCTTc().addNewTcPr();
            // set vertical alignment to "center"
            CTVerticalJc va = tcpr.addNewVAlign();
            va.setVal(STVerticalJc.CENTER);
            // create cell color element
            CTShd ctshd = tcpr.addNewShd();
            ctshd.setColor("auto");
            ctshd.setVal(STShd.CLEAR);
            if (rowCt == 0) {
                // header row
                ctshd.setFill("A7BFDE");
            } else if (rowCt % 2 == 0) {
                // even row
                ctshd.setFill("D3DFEE");
            } else {
                // odd row
                ctshd.setFill("EDF2F8");
            }
            // get 1st paragraph in cell's paragraph list
            XWPFParagraph para = cell.getParagraphs().get(0);
            // create a run to contain the content
            XWPFRun rh = para.createRun();
            // style cell as desired
            if (colCt == nCols - 1) {
                // last column is 10pt Courier
                rh.setFontSize(10);
                rh.setFontFamily("Courier");
            }
            if (rowCt == 0) {
                // header row
                rh.setText("header row, col " + colCt);
                rh.setBold(true);
                para.setAlignment(ParagraphAlignment.CENTER);
            } else if (rowCt % 2 == 0) {
                // even row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            } else {
                // odd row
                rh.setText("row " + rowCt + ", col " + colCt);
                para.setAlignment(ParagraphAlignment.LEFT);
            }
            colCt++;
        }
        // for cell
        colCt = 0;
        rowCt++;
    }
    // for row
    // write the file
    FileOutputStream out = new FileOutputStream("data/Apache_styledTable.docx");
    doc.write(out);
    out.close();
    System.out.println("Process Completed Successfully");
}
Example 12
Project: tika-master  File: XWPFWordExtractorDecorator.java View source code
private void extractTable(XWPFTable table, XWPFListManager listManager, XHTMLContentHandler xhtml) throws SAXException, XmlException, IOException {
    xhtml.startElement("table");
    xhtml.startElement("tbody");
    for (XWPFTableRow row : table.getRows()) {
        xhtml.startElement("tr");
        for (ICell cell : row.getTableICells()) {
            xhtml.startElement("td");
            if (cell instanceof XWPFTableCell) {
                extractIBodyText((XWPFTableCell) cell, listManager, xhtml);
            } else if (cell instanceof XWPFSDTCell) {
                xhtml.characters(((XWPFSDTCell) cell).getContent().getText());
            }
            xhtml.endElement("td");
        }
        xhtml.endElement("tr");
    }
    xhtml.endElement("tbody");
    xhtml.endElement("table");
}