2

I am creating a table in Apache Poi in xwpf using the below code :

          XWPFTable table = doc.createTable(Countrows1+1,4);
          table.getCTTbl().getTblPr().unsetTblBorders();
          table.setInsideHBorder(XWPFTable.XWPFBorderType.DASHED, 0,0,null);
          table.setInsideVBorder(XWPFTable.XWPFBorderType.DASHED,0,0, null);
          /* table header */

          table.getRow(0).getCell(0).setText("Column1");
          table.getRow(0).getCell(1).setText("Column2");
          table.getRow(0).getCell(2).setText("Column3");
          table.getRow(0).getCell(3).setText("Column");

          /* other rows to be populed here*/

I could not find any method using which we could align the table to left, centre or right of the page .Is there any way to do this?

Also the content of first row should be in bold . Is there any method to set the header as bold ?

user3436156
  • 103
  • 1
  • 2
  • 11
  • For your second question: https://stackoverflow.com/questions/27634991/how-to-format-the-text-in-a-xwpftable-in-apache-poi – golimar Oct 27 '17 at 14:56

2 Answers2

3

You can align the table using following function

public void setTableAlignment(XWPFTable table, STJc.Enum justification) {
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTJc jc = (tblPr.isSetJc() ? tblPr.getJc() : tblPr.addNewJc());
    jc.setVal(justification);
}
bbhar
  • 599
  • 5
  • 8
1

this code works for me:

public void setTableAlign(XWPFTable table,ParagraphAlignment align) {
    CTTblPr tblPr = table.getCTTbl().getTblPr();
    CTJc jc = (tblPr.isSetJc() ? tblPr.getJc() : tblPr.addNewJc());
    STJc.Enum en = STJc.Enum.forInt(align.getValue());
    jc.setVal(en);
}

And you call method like this:

XWPFTable table = documento.createTable();
setTableAlign(table, ParagraphAlignment.CENTER);
Jonathan Marin
  • 2,479
  • 1
  • 7
  • 8
  • Updated for latest version: CTTblPr tblPr = table.getCTTbl().getTblPr(); CTJcTable jc = (tblPr.isSetJc() ? tblPr.getJc() : tblPr.addNewJc()); jc.setVal(STJcTable.CENTER); – J. Dimeo Jul 24 '23 at 21:38