如何在 Java 中更改 Apache POI 中的 XWPFTableCell 边距?

Kas*_*tak 4 java apache ms-word apache-poi xwpf

我试图为此搜索太多,但没有得到想要的结果。我正在使用 Apache POI 使用 XWPF 将特定数据从 Excel 工作表复制到 MS Word 2010 文件中的表格。我已经完成了。

我想做的最后一件事是为每个单元格添加一个小的左右边距,以便文本不会粘在单元格边框上。我在互联网上搜索了所有内容,但无法这样做。也许我错过了一些东西。

Jen*_*nsS 5

您可以在表格级别设置单元格边距:

table.setCellMargins(0, 500, 0, 500);
Run Code Online (Sandbox Code Playgroud)

完整示例如下所示:

public static void main(String[] args) throws IOException {
    XWPFDocument doc = new XWPFDocument();
    FileOutputStream out = new FileOutputStream(new File(FILENAME));

    XWPFParagraph para = doc.createParagraph();
    XWPFRun run = para.createRun();

    //table
    XWPFTable table = doc.createTable();
    table.setCellMargins(0, 500, 0, 500); //set margins here

    //rows
    XWPFTableRow row1 = table.getRow(0);
    row1.getCell(0).setText("Hello1");
    row1.addNewTableCell().setText("Hello2");
    row1.addNewTableCell().setText("Hello3");

    XWPFTableRow row2 = table.createRow();
    row2.getCell(0).setText("Hello4");
    row2.getCell(1).setText("Hello5");
    row2.getCell(2).setText("Hello6");

    doc.write(out);
    out.close();
    doc.close();
}
Run Code Online (Sandbox Code Playgroud)