是否有将数据表写入文本文件或 TextBox 控件(使用等宽字体)的预定义或“简单”方法,例如 DataTable.Print():
第一栏| 栏目2| --------|--------| v1| v2| v3| v4| v5| v6|
编辑
这是一个初始版本 (vb.net) - 如果有人有兴趣或想要构建自己的:
Public Function BuildTable(ByVal dt As DataTable) As String
Dim result As New StringBuilder
Dim widths As New List(Of Integer)
Const ColumnSeparator As Char = "|"c
Const HeadingUnderline As Char = "-"c
' determine width of each column based on widest of either column heading or values in that column
For Each col As DataColumn In dt.Columns
Dim colWidth As Integer = Integer.MinValue
For Each row As DataRow In dt.Rows
Dim len As Integer = row(col.ColumnName).ToString.Length
If len > colWidth Then
colWidth = len
End If
Next
widths.Add(CInt(IIf(colWidth < col.ColumnName.Length, col.ColumnName.Length + 1, colWidth + 1)))
Next
' write column headers
For Each col As DataColumn In dt.Columns
result.Append(col.ColumnName.PadLeft(widths(col.Ordinal)))
result.Append(ColumnSeparator)
Next
result.AppendLine()
' write heading underline
For Each col As DataColumn In dt.Columns
Dim horizontal As String = New String(HeadingUnderline, widths(col.Ordinal))
result.Append(horizontal.PadLeft(widths(col.Ordinal)))
result.Append(ColumnSeparator)
Next
result.AppendLine()
' write each row
For Each row As DataRow In dt.Rows
For Each col As DataColumn In dt.Columns
result.Append(row(col.ColumnName).ToString.PadLeft(widths(col.Ordinal)))
result.Append(ColumnSeparator)
Next
result.AppendLine()
Next
Return result.ToString()
End Function