將資料庫查詢結果以固定欄數 (如 4 欄) 的 HTML 表格呈現,常用於商品目錄、圖片牆、會員名冊等。
Function RenderRecordsetAsTable(rs, cols, fields, Optional emptyCellHtml = " ")
' rs: 已開啟的 Recordset (游標型態建議 adOpenStatic + adLockReadOnly)
' cols: 每列欄數 (Integer)
' fields: 要顯示的欄位名陣列 或 逗號分隔字串
' emptyCellHtml: 最後一列不足時填充的 HTML
Dim arrFields, fieldCount, total, rendered, i, colIdx, html
If IsArray(fields) Then
arrFields = fields
Else
arrFields = Split(fields, ",")
End If
fieldCount = UBound(arrFields) + 1
' 先取得總筆數 (支援不支援 RecordCount 的游標)
On Error Resume Next
total = rs.RecordCount
If Err.Number <> 0 Or total = -1 Then
rs.MoveLast: rs.MoveFirst
total = rs.RecordCount
End If
On Error GoTo 0
If total = 0 Then
RenderRecordsetAsTable = "無資料
"
Exit Function
End If
html = "" & vbCrLf
rendered = 0
colIdx = 0
html = html & "" & vbCrLf
Do Until rs.EOF
html = html & ""
For i = 0 To fieldCount - 1
html = html & rs(arrFields(i))
If i < fieldCount - 1 Then html = html & "
"
Next
html = html & " " & vbCrLf
rendered = rendered + 1
colIdx = colIdx + 1
If colIdx = cols Then
If rendered < total Then
html = html & " " & vbCrLf
Else
html = html & " " & vbCrLf
End If
colIdx = 0
End If
rs.MoveNext
Loop
' 補齊最後一列
If colIdx > 0 Then
For i = colIdx To cols - 1
html = html & "" & emptyCellHtml & " " & vbCrLf
Next
html = html & "" & vbCrLf
End If
html = html & "
"
RenderRecordsetAsTable = html
End Function
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT CustomerID, CompanyName, ContactName, City FROM Customers", conn, 3, 1 ' adOpenStatic, adLockReadOnly
Response.Write RenderRecordsetAsTable(rs, 4, "CustomerID,CompanyName,ContactName,City")
rs.Close: Set rs = Nothing
conn.Close: Set conn = Nothing
%>
cellRenderer(rs, fieldName)。<th> 迴圈輸出欄位標題。table class="grid" + @media 調整欄數。