我已经创建了一个包含3列的表和另一个包含6列的表,然后将其添加到另一个表中以使其成为一个表。我想像这样对齐3列表的第二列和6列表的第二列:
谁能告诉我如何对齐2个不同表的第二列?我正在使用iTextsharp创建表。
有多种方法可以做到这一点。我将解释两个。
设置列宽以获得所需的对齐方式。
// Table with 3 columns
PdfPTable table1 = new PdfPTable(3);
table1.SetTotalWidth(new float[] { 50, 10, 300 });
table1.AddCell("One");
table1.AddCell(" ");
table1.AddCell(" ");
// Table with 6 columns
PdfPTable table2 = new PdfPTable(6);
// Column 1 and 2 are the same widths as those of table1
// Width of columns 3-6 sum up to the width of column 3 of table1
table2.SetTotalWidth(new float[] { 50, 10, 120, 50, 10, 120 });
for (int row = 0; row < 2; row++)
{
for (int column = 0; column < 6; column++)
{
table2.AddCell(" ");
}
}
doc.Add(table1);
doc.Add(table2);
您提到了将两个表都添加到另一个表中。如果这是明确的要求,则可能:
// Outer table with 1 column
PdfPTable outer = new PdfPTable(1);
// create table1 and table2 like in the previous example
// Add both tables to the outer table
outer.AddCell(new PdfPCell(table1));
outer.AddCell(new PdfPCell(table2));
doc.Add(outer);
视觉结果与上面相同。
除了考虑两个单独的表,您还可以考虑在其中一个单元格跨越多列的这一表中。
// Table with 6 columns
PdfPTable table = new PdfPTable(6);
table.SetWidths(new float[] { 50, 10, 120, 50, 10, 120 });
table.AddCell("Two");
table.AddCell(" ");
// Third cell on the first row has a colspan of 4
PdfPCell cell = new PdfPCell();
cell.Colspan = 4;
table.AddCell(cell);
// Second and third row have 6 cells
for (int row = 0; row < 2; row++)
{
for (int column = 0; column < 6; column++)
{
table.AddCell(" ");
}
}
doc.Add(table);
这种方法的好处是,您不必费力在多个表之间保持列宽一致。因为这是一张表,所以列将始终对齐。