Printing a DataTable to textbox/textfile in .NET

陌路散爱 提交于 2019-12-04 07:52:36

No, there isn't. You will have to do the formatting yourself, or find a third-party library that will do this yourself.

I recommend you check out my article DataTable Formatter.
My DataTableFormatter class contains methods for formatting DataTables as character-based tables (your requirement), HTML tables, or flow document tables.

You can download the project containing the class from my website, but for convenience I will post the code here.

/// <summary>
/// Gets a string representation of the <see cref="System.Data.DataTable" />.
/// </summary>
/// <remarks>The string representation should be displayed with a monospaced font.</remarks>
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();
}

The method GetStringRepresentation(DataTable) gives results such as this


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

I should admit that this table style is cheated from the MySQL command line client.

You could use a DataTableReader:

public static string PrintTable(this DataTable dt) 
{
    DataTableReader dtReader = dt.CreateDataReader();
    StringBuilder result = new StringBuilder();
    while (dtReader.Read()) 
    {
        for (int i = 0; i < dtReader.FieldCount; i++) 
        {
            result.AppendFormat("{0} = {1}",
                dtReader.GetName(i).Trim(),
                dtReader.GetValue(i).ToString().Trim());
        }
        result.AppendLine();
    }
    dtReader.Close();
    return result.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!