Print Contents Of A DataTable

后端 未结 7 1792
再見小時候
再見小時候 2020-12-05 17:35

Currently I have code which looks up a database table through a SQL connection and inserts the top five rows into a Datatable (Table).

using(SqlCommand _cmd          


        
7条回答
  •  有刺的猬
    2020-12-05 17:51

    Building on another answer here, here's a method that converts a DataTable to CSV output and adds the column names as the first row in the output:

    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;
    }
    

    Usage example:

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

    Note that this method does not properly handle (i.e., escape) data that contains quotes or commas. But it should be sufficient as a quick and dirty way to dump a data table to the console or anywhere else for viewing.

提交回复
热议问题