如何基于二维数组创建表? [英] How to create a table based on a two-dimensional array?
问题描述
private List<List<String>> tableOverallList;
我在此列表中有一系列列表。它在每个列表中包含8个值。我需要将它放在创建的表中。我想有2列8列。对于第一行,我有这个列表。
i have a series of list in this list. it contains 8 values in each list. i need to place it in the table created. i would like to have 2 Rows with 8 columns. for the 1st Row i have this list.
String[] tableTitleList = {" Title", " (Re)set", " Obs", " Mean", " Std.Dev", " Min", " Max", " Unit"};
List<String> tabTitleList = Arrays.asList(tableTitleList);
帮我将第一个值列表放在List tableOverallList中
在第二排。我将尝试管理列表的其余部分。
help me to place the 1st list of values inside the List tableOverallList
in the 2nd Row. i will try managing with the rest of the list.
PdfPTable table = new PdfPTable(3); // 3 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 4"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 5"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 6"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 7"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 8"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(cell7);
table.addCell(cell8);
document.add(table);
推荐答案
这真的很容易。所以你有一个嵌套列表中的数据。例如:
That's really easy. So you have data in a nested list. For instance:
public List<List<String>> getData() {
List<List<String>> data = new ArrayList<List<String>>();
String[] tableTitleList = {" Title", " (Re)set", " Obs", " Mean", " Std.Dev", " Min", " Max", "Unit"};
data.add(Arrays.asList(tableTitleList));
for (int i = 0; i < 10; ) {
List<String> dataLine = new ArrayList<String>();
i++;
for (int j = 0; j < tableTitleList.length; j++) {
dataLine.add(tableTitleList[j] + " " + i);
}
data.add(dataLine);
}
return data;
}
这将返回一组数据,其中第一条记录是标题行,以下10行包含模拟数据。假设这是您拥有的数据。
This will return a set of data where the first record is a title row and the following 10 rows contain mock-up data. It is assumed that this is data you have.
现在,当您想要在表格中呈现此数据时,您可以这样做:
Now when you want to render this data in a table, you do this:
PdfPTable table = new PdfPTable(8);
table.setWidthPercentage(100);
List<List<String>> dataset = getData();
for (List<String> record : dataset) {
for (String field : record) {
table.addCell(field);
}
}
document.add(table);
结果将如下所示:
你可以找到这里有完整的源代码: ArrayToTable ,这就是生成的PDF: array_to_table.pdf
You can find the full source code here: ArrayToTable and this is the resulting PDF: array_to_table.pdf
如果你只想要2行,标题行和数据行,更改以下行:
If you only want 2 rows, a title row and a data row, change the following line:
for (int i = 0; i < 10; ) {
进入:
for (int i = 0; i < 2; ) {
我提供了一个更通用的解决方案,因为拥有通用代码更优雅。
I've provided a more generic solution because it's more elegant to have generic code.
这篇关于如何基于二维数组创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!