如何将动态单元格添加到此代码中?

时间:2017-04-08 21:08:32

标签: itext

我有这个代码从mysqlite用itext生成一个表,但是无论我在数据库中的记录,单元格的数量是静态的(只有2个),请你帮我根据数量来获取动态单元格记录?非常感谢

// Table
    PdfPTable table = new PdfPTable(2);
    // Header
    PdfPCell cell1 = new PdfPCell(new Phrase("groups"));
    PdfPCell cell2 = new PdfPCell(new Phrase("machines"));
    table.addCell(cell1);
    table.addCell(cell2);
    // Data
    db = new Database(FirstActivity.this);
    Cursor c = db.getGroupsNamesMachines();
    if (c.moveToFirst()) {
        do {
            String group = c.getString(c.getColumnIndex("groupname"));
            cell1 = new PdfPCell(new Phrase(group));
            table.addCell(cell1);
            String machine = c.getString(c.getColumnIndex("machinename"));
            cell2 = new PdfPCell(new Phrase(machine));
            table.addCell(cell2);
        } while (c.moveToNext());
    }
    document.add(table);

1 个答案:

答案 0 :(得分:1)

您将单元格与列混淆,而字段包含行。

字段数量是预先知道的。如果您有"SELECT groupname, machinename FROM groupmachines;",则您知道每条记录都有两个字段,因此您需要2列。如果您有"SELECT groupid, groupname, machinename FROM groupmachines;",则需要3列,依此类推。

预先知道记录数量。您执行查询,只要有记录,Cursor就会继续为您提供数据。这不是问题:只需在表中为每条记录添加一行。在iText中隐式添加一行:只要添加了与列数相同的单元格,就会有一个完整的行。

将表格添加到文档后,如果表格不适合单个页面,则行将分布在不同的页面上。