2017-09-23 88 views
0

我必须使用iText PDF库创建表格。该表包含3列,可以有多行。在任何行中,任何字段都可以为空或可以具有值。 我无法在iText中找到在特定列中创建单元格的方法。所以发生的情况是,如果有任何条目为空,我的下一列的数据就是第一条。 代码片段 -iText:PDFPTable - 无法在特定列中插入数据

//Printing First column data 
    if (!attributes.getJSONObject(i).isNull("First")) { 
     PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("First"), h4)); 
     table.addCell(cell); 
    } 
//Printing Second column data 
    if (!attributes.getJSONObject(i).isNull("Second ")) { 
     PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("Second "), h4)); 
     table.addCell(cell); 
    } 
//Printing Third column data 
    if (!attributes.getJSONObject(i).isNull("Third")) { 
     PdfPCell cell = new PdfPCell(new Phrase(attributes.getJSONObject(i).getString("Third"), h4)); 
     table.addCell(cell); 
    } 

我该如何处理这不针对所有可能的情况下,明确检查?

为了使用Apache POI生成excel表格,我可以很容易地做到这一点,因为我可以在一行中插入特定列的数据。我已经完成的excel代码片段 -

//Printing First column data 
    if (!attributes.getJSONObject(i).isNull("First")) { 
    row.createCell(1); //This will insert in first column 
    row.getCell(1).setCellValue(attributes.getJSONObject(i).getString("First")); 
    } 
    //Printing Second column data 
    if(!attributes.getJSONObject(i).isNull("Second")) { 
    row.createCell(2); //This will insert in second column 
    row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second")); 
    } 
    //Printing Third column data 
    if(!attributes.getJSONObject(i).isNull("Third")) { 
    row.createCell(3); //This will insert in third column 
    row.getCell(3).setCellValue(attributes.getJSONObject(i).getString("Third")); 
    } 

iText有什么方法可以实现这一目标吗? (要在特定列中插入数据)

回答

1

IText在单元格填满表格单元格时填充它们。因此,你不能跳过空单元格。但是为什么不在这种情况下简单地添加空的内容的Cell实例呢?例如。代替仅仅

if(!attributes.getJSONObject(i).isNull("Second")) { 
    row.createCell(2); //This will insert in second column 
    row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second")); 
} 

你可以做

row.createCell(2); //This will insert in second column 
if(!attributes.getJSONObject(i).isNull("Second")) { 
    row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second")); 
} 

或可能

row.createCell(2); //This will insert in second column 
if(!attributes.getJSONObject(i).isNull("Second")) { 
    row.getCell(2).setCellValue(attributes.getJSONObject(i).getString("Second")); 
} else { 
    row.getCell(2).setCellValue(""); 
}