36

目前我有通过 SQL 连接查找数据库表并将前五行插入数据表(表)的代码。

using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
    DataTable Table = new DataTable("TestTable");

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _con.Open();
    _dap.Fill(Table);
    _con.Close();
}

然后如何将此表的内容打印到控制台以供用户查看?

在挖掘之后,我是否可以将内容绑定到列表视图,或者有没有办法直接打印它们?在这个阶段我不关心设计,只关心数据。

任何指针都会很棒,谢谢!

4

10 回答 10

53

你可以试试这段代码:

foreach(DataRow dataRow in Table.Rows)
{
    foreach(var item in dataRow.ItemArray)
    {
        Console.WriteLine(item);
    }
}

更新 1

DataTable Table = new DataTable("TestTable");
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
    _con.Open();
    _dap.Fill(Table);
    _con.Close();

}
Console.WriteLine(Table.Rows.Count);
foreach(DataRow dataRow in Table.Rows)
{
    foreach(var item in dataRow.ItemArray)
    {
        Console.WriteLine(item);
    }
}
于 2013-03-21T12:49:25.087 回答
10

这是另一种将表格转储为逗号分隔字符串的解决方案:

using System.Data;

public static string DumpDataTable(DataTable table)
        {
            string data = string.Empty;
            StringBuilder sb = new StringBuilder();

            if (null != table && null != table.Rows)
            {
                foreach (DataRow dataRow in table.Rows)
                {
                    foreach (var item in dataRow.ItemArray)
                    {
                        sb.Append(item);
                        sb.Append(',');
                    }
                    sb.AppendLine();
                }

                data = sb.ToString();
            }
            return data;
        }
于 2017-07-17T20:52:24.150 回答
5

正确的表格显示

static void print_results(DataTable data)
    {
        Console.WriteLine();
        Dictionary<string, int> colWidths = new Dictionary<string, int>();

        foreach (DataColumn col in data.Columns)
        {
            Console.Write(col.ColumnName);
            var maxLabelSize = data.Rows.OfType<DataRow>()
                    .Select(m => (m.Field<object>(col.ColumnName)?.ToString() ?? "").Length)
                    .OrderByDescending(m => m).FirstOrDefault();

            colWidths.Add(col.ColumnName, maxLabelSize);
            for (int i = 0; i < maxLabelSize - col.ColumnName.Length + 10; i++) Console.Write(" ");
        }

        Console.WriteLine();

        foreach (DataRow dataRow in data.Rows)
        {
            for (int j = 0; j < dataRow.ItemArray.Length; j++)
            {
                Console.Write(dataRow.ItemArray[j]);
                for (int i = 0; i < colWidths[data.Columns[j].ColumnName] - dataRow.ItemArray[j].ToString().Length + 10; i++) Console.Write(" ");
            }
            Console.WriteLine();
        }
    }
于 2020-09-16T02:12:28.733 回答
3

这是由包含单个表的数据表完成的

        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from info", con);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();
        ad.Fill(dt);
        Console.WriteLine(dt.Columns[0].ColumnName.ToString());
        Console.WriteLine(dt.Rows[1].ItemArray[0].ToString());

这是由包含一组表的数据集完成的

        SqlConnection con = new SqlConnection(constr);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from info", con);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);

        DataSet dt = new DataSet();
        ad.Fill(dt);
        Console.WriteLine(dt.Tables[0].Columns[0].ColumnName.ToString());
        Console.WriteLine(dt.Tables[0].Rows[0].ItemArray[0].ToString());

两者都会给出相同的结果。只有数据集包含表的索引数。

于 2018-05-16T10:06:05.547 回答
3
foreach (DataRow dr in myDataTable.Rows)
{
    foreach (var item in dr.ItemArray)
    {
        Console.Write(item + " ");
    }
    Console.WriteLine();
}

1以前的答案与此类似,但没有明确格式化行条目和单元格之间的分隔

于 2021-05-02T11:31:52.960 回答
1

打印带列的数据表内容行

Here is solution 

DataTable datatableinfo= new DataTable();

// Fill data table 

//datatableinfo=fill by function or get data from database

//Print data table with rows and column


for (int j = 0; j < datatableinfo.Rows.Count; j++)
{
    for (int i = 0; i < datatableinfo.Columns.Count; i++)    
        {    
            Console.Write(datatableinfo.Columns[i].ColumnName + " ");    
            Console.WriteLine(datatableinfo.Rows[j].ItemArray[i]); 
        }
}


Ouput :
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
ColumnName - row Value
于 2018-04-24T11:37:43.407 回答
1

使用以下扩展方法 (C# 9.0):

/// <summary>
/// Provides extension methods for the <see cref="DataTable"/> type.
/// </summary>
public static class DataTableExtensions
{
    /// <summary>
    /// Generates a textual representation of <paramref name="table"/>.
    /// </summary>
    /// <param name="table">The table to print.</param>
    /// <returns>A textual representation of <paramref name="table"/>.</returns>
    public static String Print(this DataTable table)
    {
        String GetCellValueAsString(DataRow row, DataColumn column)
        {
            var cellValue = row[column];
            var cellValueAsString = cellValue is null or DBNull ? "{{null}}" : cellValue.ToString();

            return cellValueAsString;
        }

        var columnWidths = new Dictionary<DataColumn, Int32>();

        foreach (DataColumn column in table.Columns)
        {
            columnWidths.Add(column, column.ColumnName.Length);
        }

        foreach (DataRow row in table.Rows)
        {
            foreach (DataColumn column in table.Columns)
            {
                columnWidths[column] = Math.Max(columnWidths[column], GetCellValueAsString(row, column).Length);
            }
        }

        var resultBuilder = new StringBuilder();

        resultBuilder.Append("| ");

        foreach (DataColumn column in table.Columns)
        {
            resultBuilder.Append(column.ColumnName.PadRight(columnWidths[column]));
            resultBuilder.Append(" | ");
        }

        resultBuilder.AppendLine();

        foreach (DataRow row in table.Rows)
        {
            resultBuilder.Append("| ");

            foreach (DataColumn column in table.Columns)
            {
                resultBuilder.Append(GetCellValueAsString(row, column).PadRight(columnWidths[column]));
                resultBuilder.Append(" | ");
            }

            resultBuilder.AppendLine();
        }

        return resultBuilder.ToString();
    }
}
于 2021-10-22T15:06:12.497 回答
0

基于此处的另一个答案,这是一种将 DataTable 转换为 CSV 输出并将列名添加为输出中的第一行的方法:

public static string DataTableToCsv(DataTable table)
{
    string result = string.Empty;
    StringBuilder resultBuilder = new StringBuilder();

    if (table != null && table.Rows != null && table.Columns != null && table.Columns.Count > 0)
    {
        int lastItemIndex = table.Columns.Count - 1;
        int index = 0;

        foreach (DataColumn column in table.Columns)
        {
            resultBuilder.Append(column.ColumnName);

            if (index < lastItemIndex)       // if not the last element in the row
                resultBuilder.Append(", ");  // add the separator

            index++;
        }

        resultBuilder.AppendLine();  // add a CRLF after column names row

        foreach (DataRow dataRow in table.Rows)
        {
            lastItemIndex = dataRow.ItemArray.Length - 1;
            index = 0;

            foreach (object item in dataRow.ItemArray)
            {
                resultBuilder.Append(item);

                if (index < lastItemIndex)       // if not the last element in the row
                    resultBuilder.Append(", ");  // add the separator

                index++;
            }

            resultBuilder.AppendLine();  // add a CRLF after each data row
        }

        result = resultBuilder.ToString();
    }

    return result;
}

使用示例:

DataTable table = new DataTable();
....
Console.WriteLine(DataTableToCsv(table));

请注意,此方法不能正确处理(即转义)包含引号或逗号的数据。但它应该足以作为一种快速而肮脏的方式将数据表转储到控制台或其他任何地方进行查看。

于 2020-04-07T15:13:47.947 回答
0

使用以下扩展方法。

public static string ToCSV(this DataTable t, bool header)
{
    StringBuilder sb = new StringBuilder();
    int i = 0;
    int maxColIdx = 0;
    
    if (t?.Columns?.Count > 0)
    {
        maxColIdx = t.Columns.Count - 1;
        if (header)
        {
            foreach (DataColumn c in t.Columns)
            {
                sb.Append(c.ColumnName);
                if (i < maxColIdx) sb.Append(", ");
                i++;
            }
            sb.AppendLine();
        }

        if (t?.Rows?.Count > 0)
        {
            foreach (DataRow r in t.Rows)
            {
                i = 0;
                foreach (var item in r.ItemArray)
                {
                    sb.Append(item);
                    if( i < maxColIdx) sb.Append(',');
                    i++;
                }
                sb.AppendLine();
            }
        }
    }           
    return sb.ToString();
}

于 2020-08-24T00:31:08.320 回答
0

打印 DataTable 和 DataRow 的函数。

    private void printDataTable(DataTable Table)
    {
        foreach (DataRow dataRow in Table.Rows)
        {
            printDataRow(dataRow);
        }
    }

    private void printDataRow(DataRow drow)
    {

        StringBuilder sb = new StringBuilder();

        sb.AppendLine(string.Join(",", drow.ItemArray));
        Console.WriteLine(sb);

    }
于 2021-05-10T19:44:55.437 回答