Example usage for org.apache.poi.xwpf.usermodel XWPFTableCell getCTTc

List of usage examples for org.apache.poi.xwpf.usermodel XWPFTableCell getCTTc

Introduction

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

Prototype

@Internal
    public CTTc getCTTc() 

Source Link

Usage

From source file:AkashApplications.src.GenerateInvoice.java

public boolean printInvoice(boolean printCommand)
        throws FileNotFoundException, InvalidFormatException, IOException {

    XWPFDocument document = new XWPFDocument();
    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    CTPageMar pageMar = sectPr.addNewPgMar();
    pageMar.setLeft(BigInteger.valueOf(720L));
    pageMar.setTop(BigInteger.valueOf(460L));
    pageMar.setRight(BigInteger.valueOf(720L));
    pageMar.setBottom(BigInteger.valueOf(460L));

    XWPFParagraph dateP = document.createParagraph();
    XWPFRun dateRun = dateP.createRun();
    dateRun.addBreak();/*from w w w . j a  v  a 2s  .  com*/
    dateRun.setText(copyType);
    dateRun.setFontSize(8);
    dateRun.setItalic(true);
    dateP.setAlignment(ParagraphAlignment.RIGHT);
    dateRun.addBreak();

    XWPFParagraph title = document.createParagraph();
    XWPFRun titleRun = title.createRun();
    titleRun.addBreak();
    titleRun.setText("Delivery Challan");
    titleRun.setBold(true);
    title.setAlignment(ParagraphAlignment.CENTER);
    titleRun.addBreak();

    //header table
    XWPFTable productTable = document.createTable();
    productTable.setCellMargins(50, 50, 50, 50);
    productTable.getCTTbl().getTblPr().unsetTblBorders();
    productTable.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(11000));

    XWPFTableRow row1 = productTable.getRow(0);

    XWPFTableCell cellSellerBuyer = row1.getCell(0);
    cellSellerBuyer.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(5000));

    CTTc ctTc = cellSellerBuyer.getCTTc();
    CTTcPr tcPr = ctTc.getTcPr();
    CTTcBorders border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    //        border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    XWPFParagraph seller = cellSellerBuyer.addParagraph();
    XWPFRun sellerRun = seller.createRun();
    seller.setAlignment(ParagraphAlignment.LEFT);
    sellerRun.setText("Buyer :");
    sellerRun.addBreak();
    String[] ar = buyerAddress.split("\n");
    for (String s : ar) {
        sellerRun.setText(s);
        sellerRun.addBreak();
    }

    XWPFTableCell cellProductDesc = row1.createCell();
    cellProductDesc.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(6000));

    ctTc = cellProductDesc.getCTTc();
    tcPr = ctTc.getTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    //border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    XWPFParagraph productDesc = cellProductDesc.addParagraph();
    productDesc.setAlignment(ParagraphAlignment.LEFT);
    XWPFRun runInvoice = productDesc.createRun();

    //        if(table.getRowCount() == 1)
    //        {
    //            runInvoice.addTab();
    //            runInvoice.addTab();
    //            runInvoice.addTab();
    //            String imgLoc = "Barcodes/"+ dtm.getValueAt(0, 6) +".jpg";
    //            FileInputStream image = new FileInputStream(imgLoc);
    //            runInvoice.addPicture(image, XWPFDocument.PICTURE_TYPE_JPEG,imgLoc, Units.toEMU(200), Units.toEMU(50));
    //            runInvoice.addBreak();
    //            runInvoice.addBreak();
    //        }

    runInvoice.setText("Delivery Note : ");
    runInvoice.addTab();
    runInvoice.setText(invoiceNote);
    runInvoice.addBreak();
    runInvoice.addBreak();
    runInvoice.addBreak();
    runInvoice.setText("Date : ");
    runInvoice.addTab();
    runInvoice.setText(date);
    runInvoice.addBreak();
    runInvoice.addBreak();
    //document.createParagraph().createRun().addBreak();

    XWPFTable productDetails = document.createTable();
    productDetails.setCellMargins(50, 50, 50, 50);
    //productDetails.getCTTbl().getTblPr().addNewJc().setVal(STJc.RIGHT);
    productDetails.getCTTbl().getTblPr().unsetTblBorders();
    productDetails.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(11000));

    XWPFTableRow pDetailHeader = productDetails.getRow(0);

    XWPFTableCell header0 = pDetailHeader.getCell(0);
    header0.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1000));
    XWPFParagraph headerText = header0.addParagraph();
    XWPFRun run = headerText.createRun();
    run.setText("Sl. No.");
    run.setBold(true);
    ctTc = header0.getCTTc();
    tcPr = ctTc.addNewTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    XWPFTableCell header1 = pDetailHeader.createCell();
    header1.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(8000));
    XWPFParagraph headerText1 = header1.addParagraph();
    XWPFRun run1 = headerText1.createRun();
    run1.setText("Description of Goods");
    run1.setBold(true);
    ctTc = header1.getCTTc();
    tcPr = ctTc.addNewTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    XWPFTableCell header4 = pDetailHeader.createCell();
    header4.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));
    XWPFParagraph headerText4 = header4.addParagraph();
    XWPFRun run4 = headerText4.createRun();
    run4.setText("Quantity");
    run4.setBold(true);
    ctTc = header4.getCTTc();
    tcPr = ctTc.addNewTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    for (int i = 0; i < 1; i++) {
        XWPFTableRow fTableRow = productDetails.createRow();
        for (int j = 0; j < 4; j++) {
            XWPFTableCell cell = fTableRow.getCell(j);
            try {
                ctTc = cell.getCTTc();
                tcPr = ctTc.addNewTcPr();
                border = tcPr.addNewTcBorders();
                //border.addNewBottom().setVal(STBorder.SINGLE);
                border.addNewRight().setVal(STBorder.SINGLE);
                border.addNewLeft().setVal(STBorder.SINGLE);
                if (i == 0)
                    border.addNewTop().setVal(STBorder.SINGLE);
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }

            switch (j) {
            case 0:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1000));
                break;
            case 1:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(8000));
                break;
            case 2:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));
                break;

            }

        }
    }

    int qty = 0;

    for (int i = 0; i < table.getRowCount(); i++) {
        XWPFTableRow fTableRow = productDetails.createRow();
        for (int j = 0; j < table.getColumnCount() - 1; j++) {
            XWPFTableCell cell = fTableRow.getCell(j);
            try {
                ctTc = cell.getCTTc();
                tcPr = ctTc.addNewTcPr();
                border = tcPr.addNewTcBorders();
                if (i == table.getRowCount() - 1)
                    border.addNewBottom().setVal(STBorder.SINGLE);
                border.addNewRight().setVal(STBorder.SINGLE);
                border.addNewLeft().setVal(STBorder.SINGLE);
                //                    border.addNewTop().setVal(STBorder.SINGLE); 
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }

            switch (j) {
            case 0:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1000));
                cell.setText(String.valueOf(dtm.getValueAt(i, j)));
                break;
            case 1:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(8000));
                cell.setText(String.valueOf(dtm.getValueAt(i, j)));
                break;
            case 2:
                cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));
                cell.setText(String.valueOf(dtm.getValueAt(i, j)));
                qty += Integer.parseInt(String.valueOf(dtm.getValueAt(i, j)));
                break;

            }

        }
    }

    XWPFTableRow finalRow = productDetails.createRow();
    XWPFTableCell fc0 = finalRow.getCell(0);
    fc0.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(1000));

    XWPFTableCell fc3 = finalRow.getCell(1);
    fc3.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(8000));
    XWPFParagraph fp1 = fc3.addParagraph();
    XWPFRun fRun1 = fp1.createRun();
    fRun1.setBold(true);
    fRun1.setText("TOTAL");

    XWPFTableCell fc4 = finalRow.getCell(2);
    fc4.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));
    XWPFParagraph fp2 = fc4.addParagraph();
    XWPFRun fRun2 = fp2.createRun();
    fRun2.setBold(true);
    fRun2.setText(String.valueOf(qty));

    ctTc = fc0.getCTTc();
    tcPr = ctTc.getTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    //border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    ctTc = fc3.getCTTc();
    tcPr = ctTc.getTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    //border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    ctTc = fc4.getCTTc();
    tcPr = ctTc.getTcPr();
    border = tcPr.addNewTcBorders();
    border.addNewBottom().setVal(STBorder.SINGLE);
    border.addNewRight().setVal(STBorder.SINGLE);
    border.addNewLeft().setVal(STBorder.SINGLE);
    border.addNewTop().setVal(STBorder.SINGLE);

    XWPFParagraph netPMethod = document.createParagraph();
    XWPFRun pMethodRun = netPMethod.createRun();
    pMethodRun.addBreak();
    pMethodRun.addBreak();
    pMethodRun.setItalic(true);
    pMethodRun.setFontSize(10);
    pMethodRun.setText("NB. - Goods sold to the above buyer is in " + paymentType + ".");

    try {

        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdir();
        }
        FileOutputStream outputStream = new FileOutputStream(filePath + File.separator + "Challan"
                + invoiceNote.replace("/", "_") + copyType.replace("/", "_") + ".docx");
        document.write(outputStream);
        outputStream.close();
        new InvoiceNoteManager().setProperty();
        if (printCommand)
            printDocument();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    return true;
}

From source file:br.com.techne.gluonsoft.eowexport.builder.WordBuilder.java

License:Apache License

/**
 * adiciona linha  tabela/*  www. j a v a2  s  .c o m*/
 * @param rows
 * @param data
 * @param indexRow
 * @param vcutil
 * @param columnIndex
 */
private static void addRow(List<XWPFTableRow> rows, HashMap<String, Object> data, int indexRow,
        ValueCellUtil vcutil, String[] columnIndex) {
    //adicionando titulo
    XWPFTableRow row = rows.get(indexRow);
    // 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();

    List<String> keysAttribs = null;
    if (columnIndex.length == 0) {
        keysAttribs = Arrays.asList(data.keySet().toArray(new String[0]));
        Collections.reverse(keysAttribs);
    } else {
        keysAttribs = Arrays.asList(columnIndex);
    }

    //List<String> keysAttribs = Arrays.asList(data.keySet().toArray(new String[0]));
    //Collections.reverse(keysAttribs);
    int colCt = 0;//counter cells

    // 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);

        //zebrando tabela
        if (indexRow % 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();

        if (data.get(keysAttribs.get(colCt)) == null) {
            data.put(keysAttribs.get(colCt), "");
        } else {
            // other rows
            rh.setText(vcutil.parseValue(data.get(keysAttribs.get(colCt))).toString());
            para.setAlignment(ParagraphAlignment.LEFT);
        }

        colCt++;
    } // for cell
}

From source file:br.com.techne.gluonsoft.eowexport.builder.WordBuilder.java

License:Apache License

/**
 * adiciona titulo/*from  w  w w . j  a  v a  2  s  .  c om*/
 * @param rows
 * @param titles
 */
private static void addTitle(List<XWPFTableRow> rows, String[] titles) {
    //adicionando titulo
    XWPFTableRow row = rows.get(0);
    // 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();
    int colCt = 0;

    //CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
    //tblWidth.setW(BigInteger.valueOf(200));
    //tblWidth.setType(STTblWidth.DXA);

    // add content to each cell
    for (XWPFTableCell cell : cells) {
        // get a table cell properties element (tcPr)
        CTTcPr tcpr = cell.getCTTc().addNewTcPr();
        //tcpr.setTcW(tblWidth);

        // 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);
        // header row
        ctshd.setFill("A7BFDE");
        // 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();

        // header row
        if ((titles.length - 1) < colCt) {
            rh.setText("");
        } else
            rh.setText(titles[colCt]);

        rh.setBold(true);
        para.setAlignment(ParagraphAlignment.CENTER);

        colCt++;
    } // for cell
}

From source file:com.bxf.hradmin.testgen.service.impl.DocxTestGenerator.java

License:Open Source License

private void writeQuestionNo(Integer questionNo, XWPFTableRow row) {
    XWPFTableCell cell = row.getCell(0);
    XWPFParagraph paragraph = cell.getParagraphs().get(0);
    adjustLineHeight(paragraph);/* w  w w  .jav  a2s. co m*/
    // 
    paragraph.setAlignment(ParagraphAlignment.CENTER);
    // 
    cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(735));

    XWPFRun run = createRun(paragraph);
    run.setText(String.valueOf(questionNo));
}

From source file:com.deepoove.poi.NiceXWPFDocument.java

License:Apache License

public void mergeCellsHorizonal(XWPFTable table, int row, int fromCol, int toCol) {

    for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {

        XWPFTableCell cell = table.getRow(row).getCell(colIndex);
        CTTcPr tcPr = cell.getCTTc().getTcPr();
        if (null == tcPr)
            tcPr = cell.getCTTc().addNewTcPr();
        CTHMerge hMerge = tcPr.addNewHMerge();
        if (colIndex == fromCol) {
            // The first merged cell is set with RESTART merge value
            hMerge.setVal(STMerge.RESTART);
        } else {/*from  w  ww .  j  av  a  2s  . co  m*/
            // Cells which join (merge) the first one, are set with CONTINUE
            hMerge.setVal(STMerge.CONTINUE);
        }
    }
}

From source file:com.deepoove.poi.NiceXWPFDocument.java

License:Apache License

public void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {

    for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {

        XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
        CTTcPr tcPr = cell.getCTTc().getTcPr();
        if (null == tcPr)
            tcPr = cell.getCTTc().addNewTcPr();
        CTVMerge vMerge = tcPr.addNewVMerge();
        if (rowIndex == fromRow) {
            // The first merged cell is set with RESTART merge value
            vMerge.setVal(STMerge.RESTART);
        } else {//from w w  w.  jav  a  2s. c  o m
            // Cells which join (merge) the first one, are set with CONTINUE
            vMerge.setVal(STMerge.CONTINUE);
        }
    }
}

From source file:com.deepoove.poi.NiceXWPFDocument.java

License:Apache License

@Deprecated
public void spanCellsAcrossRow(XWPFTable table, int rowNum, int colNum, int span) {
    XWPFTableCell cell = table.getRow(rowNum).getCell(colNum);
    cell.getCTTc().getTcPr().addNewGridSpan();
    cell.getCTTc().getTcPr().getGridSpan().setVal(BigInteger.valueOf((long) span));
}

From source file:com.deepoove.poi.tl.SimpleTable.java

License:Apache License

/**
 * 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.
        // www  .ja va  2s .c o m
 * @throws Exception
 */
public static void createStyledTable() 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("styledTable.docx");
    doc.write(out);
    out.close();
}

From source file:com.foc.vaadin.gui.mswordGenerator.XWPFExtendedTable.java

License:Apache License

public XWPFExtendedTable(XWPFTableCell cell) {
    ctTbl = cell.getCTTc().addNewTbl();

    /* definition du style du tableau */
    CTTblPr tblPr = ctTbl.addNewTblPr();
    CTString style = tblPr.addNewTblStyle();
    style.setVal("Grilledutableau");
    CTTblWidth tblW = tblPr.addNewTblW();
    tblW.setW(new BigInteger("0"));
    tblW.setType(STTblWidth.AUTO);/*from   ww w.  j av  a2 s .c  om*/

    /* Creation d'un paragraph (Obligatoire pour eviter les erreur de lecture) */
    cell.getCTTc().addNewP();
}

From source file:com.glodon.tika.SimpleTable.java

License:Apache License

/**
 * 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.
        //from   w  ww.  j  a va  2  s .co m
 * @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();
    }
}