您的位置:首页 > 其它

[随记]占位替换生成表格table源码

2017-10-06 00:00 141 查看

前言

有时候想代码中生成网页table源码,无奈拿到的数据是按列存储的。此时不妨考虑使用占位替换的策略,也不用对数据的预处理再按行遍历生产源码。

具体代码

package html.david.table;

import java.util.ArrayList;
import java.util.List;

public class GenerateHtmlTable {

public static void main(String[] args) {
// TODO Auto-generated method stub
/** * 每一个list<String>存储的是一个列数据 */
int rowNum = 5;
int colNum = 6;
List<List<String>> datas = new ArrayList<List<String>>();
//构造数据
for(int row=0;row<rowNum;row++){
List<String> cols = new ArrayList<String>();
for(int col=0;col<colNum;col++)
cols.add(row+" "+col);
datas.add(cols);
}
System.out.println(generateHtmlTable(datas,5,6));
}

public static String generateHtmlTable(List<List<String>>datas,int rowNum,int colNum){
//产生相应的html
String resultHtml = "<table>";
resultHtml += "<th>colume1</th>";
resultHtml += "<th>colume2</th>";
resultHtml += "<th>colume3</th>";
resultHtml += "<th>colume4</th>";
resultHtml += "<th>colume5</th>";
resultHtml += "<th>colume6</th>";
for(int row=0;row < rowNum;row++){
resultHtml += "<tr style='border:5px solid red;'>";
for(int col=0;col < colNum;col++){
resultHtml += "<td style='border:5px solid green;'>";
resultHtml += row+"-"+col;  //此处作为占位符 定义为唯一的格式 以便后面的替换
resultHtml += "</td>";
}
resultHtml += "</tr>";
}
resultHtml += "</table>";

//数据显示部分
for(int row = 0;row < rowNum;row++){
List<String> cols = datas.get(row);
for(int col = 0;col < colNum; col++){
resultHtml = resultHtml.replace(col+"-"+row, cols.get(col));
}
}
return resultHtml;
}

}

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: