阿帕奇Poi。如何使 Word 文档中的表格居中?

问题描述 投票:0回答:1

关于如何将表格中单元格的内容居中的答案有很多。但我想将整个桌子居中。

当我创建这样的表时:

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

它会自动左对齐。我知道对于文本,我创建一个段落,创建一个运行,添加一个 CT 对象和一个 PR 对象并在那里设置 hAlign。 XWPFTable 有类似的方法:

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

但是我在 CTTblPr 的 JavaDoc 中没有看到任何与水平对齐有关的内容。

ms-word apache-poi center
1个回答
0
投票

当前 Apache POI 版本 5.2.5 提供 XWPFTable.setTableAlignment。它设置 TableRowAlign

完整示例:

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

 }
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.