我必须使用iText PDF库创建一个表。该表包含3列,可以有多行。在任何行中,任何字段都可以为空或可以具有值。 我无法在iText中找到在特定列中创建单元格的方法。所以正在发生的事情是,如果任何条目为空,我的下一列数据将出现在第一列。 代码段 -
//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有什么方法可以达到这个目的吗? (在特定列中插入数据)
答案 0 :(得分: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("");
}