首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用java中的apache poi在word中设置表的尺寸和间距

如何使用java中的apache poi在word中设置表的尺寸和间距
EN

Stack Overflow用户
提问于 2020-08-21 05:24:38
回答 1查看 1.2K关注 0票数 0

我正在尝试用表格生成一个word文档。只有一个页面,它有5行2列。我用的是信页,大小是8.5“x11”。我给了这个节目的空白。

这是我的密码

代码语言:javascript
运行
复制
    XWPFDocument xWPFDocument = new XWPFDocument();

    CTSectPr cTSectPr = xWPFDocument.getDocument().getBody().addNewSectPr();
    CTPageMar cTPageMar = cTSectPr.addNewPgMar();
    cTPageMar.setLeft(BigInteger.valueOf(475));
    cTPageMar.setTop(BigInteger.valueOf(720));
    cTPageMar.setRight(BigInteger.valueOf(446));
    cTPageMar.setBottom(BigInteger.valueOf(605));

    XWPFTable xWPFTable = xWPFDocument.createTable(5, 2);
    xWPFTable.getCTTbl().getTblPr().unsetTblBorders();

    xWPFTable.setTableAlignment(TableRowAlign.CENTER);
    xWPFTable.setWidth("100%");

使用以下代码设置单元格宽度和行高。但我没有注意到任何变化。

代码语言:javascript
运行
复制
    XWPFTableRow xWPFTableRow;

    for (int i = 0; i < 5; i++) {
        xWPFTableRow = xWPFTable.getRow(i);

        xWPFTableRow.setHeight(2880);
        xWPFTableRow.getCell(i).getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(6033));
    }

我要找的是如何设置Horizontal and Vertical Spacing,还有使用Apache设置Horizontal and Vertical Pitch的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-21 17:28:19

当前的apache poi 4.1.2提供了一个方法setWidth(java.lang.String widthValue),其中widthValue可以是在XWPFTableXWPFTableCell中提供百分比宽度的String

直到现在才直接支持设置单元格间距。因此,必须为此使用底层的ooxml-schemas类。

完整的例子:

代码语言:javascript
运行
复制
import java.io.FileOutputStream;

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

public class CreateWordTableCellSpacing {

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

  XWPFDocument document = new XWPFDocument();

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

  int cols = 3;
  int rows = 3;
  XWPFTable table = document.createTable(rows, cols);

  table.setWidth("100%");
  table.getRow(0).getCell(0).setWidth("20%");
  table.getRow(0).getCell(1).setWidth("30%");
  table.getRow(0).getCell(2).setWidth("50%");

  //set spacing between cells
  table.getCTTbl()
   .getTblPr()
   .addNewTblCellSpacing()
   .setType(
     org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth.DXA
   );
  table.getCTTbl()
   .getTblPr()
   .getTblCellSpacing()
   .setW(java.math.BigInteger.valueOf(
     180 // 180 TWentieths of an Inch Point (Twips) = 180/20 = 9 pt = 9/72 = 0.125"
   ));

  paragraph = document.createParagraph();

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

 }
}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63516969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档