嘿伙计们,我想在HTML表格中显示ResultSet中的数据..这是我的代码
while(result.next()){
writer.println("<table BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>"
+ "<tr><th>FIRSTNAME</th><th>LASTNAME</th></tr>"
+ "<tr><td><center>"+result.getString("firstname")+"</center></td>"
+ "<td><center>"+result.getString("lastname")+"</center></td></tr> </table>");
}
但它不适合多行...所以任何帮助?
答案 0 :(得分:1)
这样的事情怎么样?
writer.println("<table BORDER=1 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>"
+"<tr><th>FIRSTNAME</th><th>LASTNAME</th></tr>");
while(result.next()){
writer.println("<tr><td><center>"+result.getString("firstname")+"</center></td>"
+ "<td><center>"+result.getString("lastname")+"</center></td></tr>");
}
writer.println("</table>");
答案 1 :(得分:1)
将最后一行放在循环外
答案 2 :(得分:0)
将ResultSet对象转换为HTML内容的步骤
(1)将包导入到JAVA类文件中
(2)创建一个类类型为“ HtmlReportGenerator”的对象
(3)将表名称设置为字符串
(4)将列名设置为逗号分隔的字符串
(5)以ResultSet对象,表名和列名作为参数调用“ toHTMLTable()”方法
Example:
import frizbee.beach.*;
//Inside Class file
HtmlReportGenerator hrp=new HtmlReportGenerator();
String columnNames="col1,col2,col3,col4,col5,col6,col7,col8,col9";
String tableName="abcde";
String html=hrp.toHTMLTable(rs,tableName,columnNames);
System.out.println(html);
@SuppressWarnings("unchecked")
public String toHTMLTable(ResultSet rs,String tableName,String columnNames) throws JSONException, SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
JSONArray json = new JSONArray();
while(rs.next()) {
LinkedHashMap<String, Object> lhm = new LinkedHashMap<String, Object>();
for (int i=1; i<=numColumns; i++) {
String column_name = rsmd.getColumnLabel(i);
//String value= rs.getObject(column_name);
lhm.put(column_name,rs.getObject(column_name));
}
json.put(lhm);
}
String[] colNames=columnNames.split(",");
StringBuilder s1=new StringBuilder();
s1.append("<div style=\"font-size:14pt;font-weight:bold;margin:15pt auto;text-align:center\">"+tableName+"</div>"
+ " <table style=\"background:white;border-collapse: collapse;text-align:center;margin:10pt auto;border-radius:4px;border:1px solid rgba(255, 30, 0, 0);width:97%\" width=\"97%\" align=\"center\">" +
" <thead style=\"background:#a6a6a6;color:white\">");
for(int i=0;i<colNames.length;i++) {
s1.append("<th style=\"padding:10pt 2pt;\">"+colNames[i]+"</th>");
}
s1.append("</thead><tbody>");
for (int i = 0; i < json.length(); i++) {
s1.append("<tr>");
JSONObject jsonObj = json.getJSONObject(i);
Iterator<String> keys = jsonObj.keys();
while (keys.hasNext()) {
String key = keys.next();
String val="";
if(jsonObj.isNull(key)) {
val="";
}
else {
val= jsonObj.get(key).toString();
}
s1.append("<td style=\"padding:7pt 2pt;border-bottom: 1px solid black !important;"+bgColor(i)+"\">"+val+"</td>");
}
s1.append("</tr>");
}
s1.append("</tbody></table>");
return s1.toString();
}
private String bgColor(int i) {
return i%2==0?"background-color:#ededed":"";
}