我需要从仅包含数据、colspan 和 rowspan 的二维数组生成 html 表。我不需要边距、高度和宽度。只有 td 和 tr。我知道表格单元格的宽度和高度,结果总是矩形的。我需要用 Java 来做,但欢迎任何提示。
这是一个示例单元格类:
public class Cell {
String label;
int colSpan, rowSpan;
public Cell(String label, int colSpan, int rowSpan) {
this.label = label;
this.colSpan = colSpan;
this.rowSpan = rowSpan;
}
}
这是一个包含数据和 rowspan/colspan 信息的二维数组的例子;
public class Test {
public static void main(String[] args) {
List<List<Cell>> rows = new ArrayList<>();
List<Cell> row1 = new ArrayList<>();
Cell cell11 = new Cell("total", 1, 9);
Cell cell12 = new Cell("mid_total", 1, 3);
Cell cell13 = new Cell("detail", 1, 1);
row1.add(cell11);
row1.add(cell12);
row1.add(cell13);
rows.add(row1);
List<Cell> row2 = new ArrayList<>();
Cell cell21 = new Cell("mid_total", 1, 3);
Cell cell22 = new Cell("detail", 1, 1);
row2.add(cell21);
row2.add(cell22);
rows.add(row2);
List<Cell> row3 = new ArrayList<>();
Cell cell31 = new Cell("mid_total", 1, 3);
Cell cell32 = new Cell("detail", 1, 1);
row3.add(cell31);
row3.add(cell32);
rows.add(row3);
List<Cell> row4 = new ArrayList<>();
Cell cell41 = new Cell("detail", 1, 1);
row4.add(cell41);
rows.add(row4);
List<Cell> row5 = new ArrayList<>();
Cell cell51 = new Cell("detail", 1, 1);
row5.add(cell51);
rows.add(row5);
List<Cell> row6 = new ArrayList<>();
Cell cell61 = new Cell("detail", 1, 1);
row6.add(cell61);
rows.add(row6);
List<Cell> row7 = new ArrayList<>();
Cell cell71 = new Cell("detail", 1, 1);
row7.add(cell71);
rows.add(row7);
List<Cell> row8 = new ArrayList<>();
Cell cell81 = new Cell("detail", 1, 1);
row8.add(cell81);
rows.add(row8);
List<Cell> row9 = new ArrayList<>();
Cell cell91 = new Cell("detail", 1, 1);
row9.add(cell91);
rows.add(row9);
}
}
它应该是这样的:
+-------+-----------+--------+
| total | mid_total | detail |
+ + +--------+
| | | detail |
+ + +--------+
| | | detail |
+ +-----------+--------+
| | mid_total | detail |
+ + +--------+
| | | detail |
+ + +--------+
| | | detail |
+ +-----------+--------+
| | mid_total | detail |
+ + +--------+
| | | detail |
+ + +--------+
| | | detail |
+-------+-----------+--------+
最佳答案
迭代二维数组中的行和列,并使用 StringBuilder
创建 HTML 标记。
public String toHTML(String[][] data){
StringBuilder sb = new StringBuilder();
sb.append("<table>\n");
for(int row = 0; row < data.length; row++){
sb.append("\t<tr>\n");
for(int col = 0; col < data[0].length; col++){
sb.append("\t\t<td>" + data[row][col] + "</td>\n");
}
sb.append("\t</tr>\n");
}
sb.append("</table>");
return sb.toString();
}
如果你这样使用它:
String[][] data = {{"r0c1", "r0c2", "r0c3"},
{"r1c1", "r1c2", "r1c3"}};
System.out.println(toHTML(data));
它将产生这个:
<table>
<tr>
<td>r0c1</td>
<td>r0c2</td>
<td>r0c3</td>
</tr>
<tr>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
</tr>
</table>
关于java - 使用 colspan 和 rowspan 从二维数组生成 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738145/