用表格輸出資料庫結果是常有的事,表格有多層結構,外層是 table 再套 tr(實際還有 tbody),再套 td,各 td 之間又可能相互影響,所以研究一下 ASP 輸出表格的演算法還是比較有趣的。
table 是最外層元素,不迴圈,使用就比較簡單了,先看只有一列的表格樣本,我們以 RecordSet 對象 rs 為資料來源,產生的結果儲存在 str 中。
dim str
str = ""
do while not rs.eof
str = str & "<tr><td>" & rs("fld") & "</td></tr>"
rs.MoveNext
loop
if str <> "" then
str = "<table>" & str & "</table>"
end if
一列的情況挺簡單的,毫無可圈可點之處,多列就複雜多了,這個樣本中我們以數組作為資料來源。主要考慮一行的開頭、一行的結尾、補充最後一行的列。
dim arr(3)
arr(0) = 1
arr(1) = 2
arr(2) = 3
arr(3) = 4
dim maxColsCnt '一行的最大列數
maxColsCnt = 3
dim colsCnt '總共已經產生了多少列
colsCnt = 0
dim str
str = ""
dim i
i = 0
do while i<=UBound(arr)
if colsCnt mod maxColsCnt = 0 then
'一行的開頭
str = str & "<tr>"
end if
str = str & "<td>" & arr(i) & "</td>"
colsCnt = colsCnt + 1
if colsCnt mod maxColsCnt = 0 then
'一行的結尾
str = str & "</tr>"
end if
i = i + 1
loop
if colsCnt mod maxColsCnt <> 0 then
'補充最後一行的列
do while colsCnt mod maxColsCnt <> 0
str = str & "<td> </td>"
colsCnt = colsCnt + 1
loop
str = str & "</tr>"
end if
if colsCnt > 0 then
str = "<table>" & str & "</table>"
end if