打印数据表的内容
本文关键字:数据表 打印 | 更新日期: 2023-09-27 18:04:58
目前我有一段代码,它通过SQL连接查找数据库表,并将前五行插入Datatable(table(中。
using(SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
DataTable Table = new DataTable("TestTable");
SqlDataAdapter _dap = new SqlDataAdapter(_cmd);
_con.Open();
_dap.Fill(Table);
_con.Close();
}
然后如何将此表的内容打印到控制台以供用户查看?
仔细研究后,我是否应该将内容绑定到列表视图,或者是否有直接打印它们的方法?现阶段我不关心设计,只关心数据。
任何指点都会很棒,谢谢!
您可以尝试以下代码:
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);
}
}
下面是另一个将表转储为逗号分隔字符串的解决方案:
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;
}
正确的表格显示
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();
}
}
foreach (DataRow dr in myDataTable.Rows)
{
foreach (var item in dr.ItemArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
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 the data of <paramref name="table"/>.
/// </summary>
/// <param name="table">The table to print.</param>
/// <returns>A textual representation of the data 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();
}
}
这是由包含单个表的数据表完成的
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());
两者都会得到相同的结果。只有数据集包含表的索引编号。
用列打印数据表内容行
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
在这里的另一个答案的基础上,这里有一个方法可以将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));
请注意,此方法无法正确处理(即转义(包含引号或逗号的数据。但是,作为一种快速而肮脏的方式,将数据表转储到控制台或其他任何地方进行查看就足够了。
使用以下扩展方法。
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();
}
打印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);
}