java - Apache poi 表 (XWPFTable) 未正确生成

标签 java apache-poi docx

关于 apache poi 有很多教程,但是我在创建表时遇到问题。 我正在尝试这段代码:

public class CreateTable
{
    public static void main(String[] args)throws Exception
    {
        //Blank Document
        XWPFDocument document= new XWPFDocument();

        //Write the Document in file system
        FileOutputStream out = new FileOutputStream(
                new File("create_table.docx"));

        //create table
        XWPFTable table = document.createTable();
        //create first row
        XWPFTableRow tableRowOne = table.getRow(0);
        tableRowOne.getCell(0).setText("col one, row one");
        tableRowOne.addNewTableCell().setText("col two, row one");
        tableRowOne.addNewTableCell().setText("col three, row one");
        //create second row
        XWPFTableRow tableRowTwo = table.createRow();
        tableRowTwo.getCell(0).setText("col one, row two");
        tableRowTwo.getCell(1).setText("col two, row two");
        tableRowTwo.getCell(2).setText("col three, row two");
        //create third row
        XWPFTableRow tableRowThree = table.createRow();
        tableRowThree.getCell(0).setText("col one, row three");
        tableRowThree.getCell(1).setText("col two, row three");
        tableRowThree.getCell(2).setText("col three, row three");

        document.write(out);
        out.close();
        System.out.println("create_table.docx written successully");
    }
}

但是在 Libre Office ubuntu 中,表格具有无限宽度,当我将其加载到 google doc 时,该文档中什么也没有。 设置表格宽度没有帮助。 我做错了什么? 请帮忙((

最佳答案

您可以通过以下方式设置宽度:

XWPFDocument doc = new XWPFDocument();
XWPFTable table = doc.createTable(1,2);
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(6000));
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2000));
table.getRow(0).getCell(0).setText("1A");
table.getRow(0).getCell(1).setText("1B");
XWPFTableRow newrow = table.createRow();
newrow.getCell(0).setText("2A");
newrow.getCell(1).setText("2B");

关于java - Apache poi 表 (XWPFTable) 未正确生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331816/

相关文章:

java - 在 JTextArea 的列中对齐字符串

java - 标记语法错误,错误放置的结构

java - 如何使用 apache poi 4.1.0 设置单元格的背景颜色

linux - 如何从 Linux 服务器的 .docx 生成 PDF 文件?

c - 如何在c中读取.docx文件

java - 如何检查给定的正则表达式是否有效?

java - POSIX_SPAWN 与 Java?

java - 如何在基于抽象语法树的解释器中表示类

java - Apache-poi : cannot add image in docx header

php - 使用 PHP 为目录中的文件显示 docx 属性(标题、标签)