ASP 输出表格的算法

作者:vkvi 来源:ITPOW(原创) 日期:2007-1-26

用表格输出数据库结果是常有的事,表格有多层结构,外层是 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
相关文章