当前位置:  开发笔记 > 后端 > 正文

在.NET中将DataTable打印到textbox/textfile

如何解决《在.NET中将DataTable打印到textbox/textfile》经验,为你挑选了1个好方法。

是否有预定义或"简单"的方法将数据表写入文本文件或TextBox控件(使用等宽字体),如DataTable.Print():

 Column1| Column2|
--------|--------|
      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

Bassem.. 5

我建议你查看我的文章DataTable Formatter.
我的DataTableFormatter类包含将DataTables格式化为基于字符的表(您的要求),HTML表或流文档表的方法.

您可以从我的网站下载包含该类的项目,但为方便起见,我将在此处发布代码.

/// 
/// Gets a string representation of the .
/// 
/// The string representation should be displayed with a monospaced font.
public static string GetStringRepresentation(DataTable dataTable)
{
    if (dataTable == null)
        throw new ArgumentNullException("'dataTable' cannot be null.");

    StringWriter representationWriter = new StringWriter();

    // First, set the width of every column to the length of its largest element.
    int[] columnWidths = new int[dataTable.Columns.Count];
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        int headerWidth = dataTable.Columns[columnIndex].ColumnName.Length;
        int longestElementWidth = dataTable.AsEnumerable()
            .Select((row) => row[columnIndex].ToString().Length)
            .Max();
        columnWidths[columnIndex] = Math.Max(headerWidth, longestElementWidth);
    }

    // Next, write the table
    // Write a horizontal line.
    representationWriter.Write("+-");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        for (int i = 0; i < columnWidths[columnIndex]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (columnIndex != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");
    // Print the headers
    representationWriter.Write("| ");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        string header = dataTable.Columns[columnIndex].ColumnName;
        representationWriter.Write(header);
        for (int blanks = columnWidths[columnIndex] - header.Length; blanks > 0; blanks--)
            representationWriter.Write(" ");
        representationWriter.Write(" | ");
    }
    representationWriter.WriteLine();
    // Print another horizontal line.
    representationWriter.Write("+-");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        for (int i = 0; i < columnWidths[columnIndex]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (columnIndex != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");

    // Print the contents of the table.
    for (int row = 0; row < dataTable.Rows.Count; row++)
    {
        representationWriter.Write("| ");
        for (int column = 0; column < dataTable.Columns.Count; column++)
        {
            representationWriter.Write(dataTable.Rows[row][column]);
            for (int blanks = columnWidths[column] - dataTable.Rows[row][column].ToString().Length;
                blanks > 0; blanks--)
                representationWriter.Write(" ");
            representationWriter.Write(" | ");
        }
        representationWriter.WriteLine();
    }

    // Print a final horizontal line.
    representationWriter.Write("+-");
    for (int column = 0; column < dataTable.Columns.Count; column++)
    {
        for (int i = 0; i < columnWidths[column]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (column != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");

    return representationWriter.ToString();
}

方法GetStringRepresentation(DataTable)给出了这样的结果


    +------------------+----------------+-------------------+
    | Item             | Units in Stock | Unit Price        |
    +------------------+----------------+-------------------+
    | Drilling machine | 1000           | $1,000,000        |
    | Backpack         | 320            | $24               |
    | Chocolate bar    | 100000         | $2.00000000000000 |
    +------------------+----------------+-------------------+

我应该承认这个表样式是从MySQL命令行客户端欺骗的.



1> Bassem..:

我建议你查看我的文章DataTable Formatter.
我的DataTableFormatter类包含将DataTables格式化为基于字符的表(您的要求),HTML表或流文档表的方法.

您可以从我的网站下载包含该类的项目,但为方便起见,我将在此处发布代码.

/// 
/// Gets a string representation of the .
/// 
/// The string representation should be displayed with a monospaced font.
public static string GetStringRepresentation(DataTable dataTable)
{
    if (dataTable == null)
        throw new ArgumentNullException("'dataTable' cannot be null.");

    StringWriter representationWriter = new StringWriter();

    // First, set the width of every column to the length of its largest element.
    int[] columnWidths = new int[dataTable.Columns.Count];
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        int headerWidth = dataTable.Columns[columnIndex].ColumnName.Length;
        int longestElementWidth = dataTable.AsEnumerable()
            .Select((row) => row[columnIndex].ToString().Length)
            .Max();
        columnWidths[columnIndex] = Math.Max(headerWidth, longestElementWidth);
    }

    // Next, write the table
    // Write a horizontal line.
    representationWriter.Write("+-");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        for (int i = 0; i < columnWidths[columnIndex]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (columnIndex != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");
    // Print the headers
    representationWriter.Write("| ");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        string header = dataTable.Columns[columnIndex].ColumnName;
        representationWriter.Write(header);
        for (int blanks = columnWidths[columnIndex] - header.Length; blanks > 0; blanks--)
            representationWriter.Write(" ");
        representationWriter.Write(" | ");
    }
    representationWriter.WriteLine();
    // Print another horizontal line.
    representationWriter.Write("+-");
    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
    {
        for (int i = 0; i < columnWidths[columnIndex]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (columnIndex != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");

    // Print the contents of the table.
    for (int row = 0; row < dataTable.Rows.Count; row++)
    {
        representationWriter.Write("| ");
        for (int column = 0; column < dataTable.Columns.Count; column++)
        {
            representationWriter.Write(dataTable.Rows[row][column]);
            for (int blanks = columnWidths[column] - dataTable.Rows[row][column].ToString().Length;
                blanks > 0; blanks--)
                representationWriter.Write(" ");
            representationWriter.Write(" | ");
        }
        representationWriter.WriteLine();
    }

    // Print a final horizontal line.
    representationWriter.Write("+-");
    for (int column = 0; column < dataTable.Columns.Count; column++)
    {
        for (int i = 0; i < columnWidths[column]; i++)
            representationWriter.Write("-");
        representationWriter.Write("-+");
        if (column != dataTable.Columns.Count - 1)
            representationWriter.Write("-");
    }
    representationWriter.WriteLine(" ");

    return representationWriter.ToString();
}

方法GetStringRepresentation(DataTable)给出了这样的结果


    +------------------+----------------+-------------------+
    | Item             | Units in Stock | Unit Price        |
    +------------------+----------------+-------------------+
    | Drilling machine | 1000           | $1,000,000        |
    | Backpack         | 320            | $24               |
    | Chocolate bar    | 100000         | $2.00000000000000 |
    +------------------+----------------+-------------------+

我应该承认这个表样式是从MySQL命令行客户端欺骗的.

推荐阅读
小妖694_807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有