Greg Br
Greg Br

Reputation: 1

Apache Poi. How do I center a table in a Word document?

There are lots of answers about how to center the contents of a cell in a table. But I want to center the entire table.

When I create a table like this:

    XWPFTable table = doc.createTable(1,rowSize);
    table.removeBorders()
    table.setWidth("80.00%")

It's automatically left justified. I know that for text I create a paragraph, create a run, add a CT object and a PR object and set the hAlign there. The XWPFTable has similar methods:

    CTTbl cttbl = table.getCTTbl()
    CTTblPr cTTblPr = cttbl.addNewTblPr()

But I don't see anything in the JavaDoc for the CTTblPr which has anything to do with horizontal alignment.

Upvotes: 0

Views: 103

Answers (1)

Axel Richter
Axel Richter

Reputation: 61945

Current Apache POI version 5.2.5 provides XWPFTable.setTableAlignment. It sets TableRowAlign.

Complete Example:

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordTableAligned {
    
 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();  
  run.setText("Text before table...");

  XWPFTable table = document.createTable(1, 3);
  table.setWidth("50%");
  
  table.setTableAlignment(TableRowAlign.CENTER);

  paragraph = document.createParagraph();
  run = paragraph.createRun();  
  run.setText("Text after table...");

  FileOutputStream out = new FileOutputStream("./CreateWordTableAligned.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

Result:

enter image description here


To answer the question about what to set using the underlying CT-classes, have a look at what XWPFTable -> public void setTableAlignment(TableRowAlign tra)is doing. It gets or adds CTJcTable (table justification) from CTTblPr. Then it sets value of STJcTable.Enum which is either LEFT, RIGHT or CENTER.

Upvotes: 2

Related Questions