代码段——关于控制台打印DataTable
0.背景说明
最近频繁使用DataTable对象,整理关于DataTable的一些方法,需要调试打印处理,故编写一个比较工整的打印方法
1.代码段
/// <summary>
/// 控制台输出DataTable
/// </summary>
/// <param name="dt">目标DataTable</param>
/// <param name="title">DataTable的标题</param>
private static void PrintDataTable(DataTable dt, string title)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"{title}");
//拼接列头
string colName = "";
foreach (DataColumn column in dt.Columns)
{
colName += "|" + PadRightEx(column.ColumnName, 20);
}
Console.WriteLine(colName);
Console.WriteLine("--------------------------------------------------------------------------------------------------------");
//循环打印每一行
foreach (DataRow row in dt.Rows)
{
//拼接行数据
string strRow = "";
foreach (var item in row.ItemArray)
{
strRow += "|" + PadRightEx(item.ToString(), 20);
}
Console.WriteLine(strRow);
}
Console.WriteLine("");
}
/// <summary>
/// 用空格将字符串拼接到指定的长度
/// 参考:https://www.cnblogs.com/chenjiahong/articles/2705437.html
/// 中文和英文字符占位宽度不一样,进行调整
/// </summary>
/// <param name="str">目标字符串</param>
/// <param name="totalByteCount">拼接后的字符串长度</param>
/// <returns></returns>
private static string PadRightEx(string str, int totalByteCount)
{
Encoding coding = Encoding.GetEncoding("gb2312");
int dcount = 0;
foreach (char ch in str.ToCharArray())
{
if (coding.GetByteCount(ch.ToString()) == 2)
dcount++;
}
string w = str.PadRight(totalByteCount - dcount);
return w;
}
2. 测试
//构建测试数据
private static DataTable GetDataTable()
{
DataTable dt = new DataTable("Student");
DataColumn dcId = new DataColumn("Id", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
DataColumn dcAge = new DataColumn("Age", typeof(int));
DataColumn dcGender = new DataColumn("Gender", typeof(bool));
DataColumn dcCreateTime = new DataColumn("CreateTime", typeof(DateTime));
DataColumn[] dataColumns = new DataColumn[] { dcId, dcName, dcAge, dcGender, dcCreateTime };
dt.Columns.AddRange(dataColumns);
dt.Rows.Add(1, "'张三'", 17, false, "2023-9-27 20:10:00");
dt.Rows.Add(2, "李四", 18, true, "2023-8-27 20:10:00");
dt.Rows.Add(3, "王五", 19, false, "2023-7-27 20:10:00");
dt.Rows.Add(4, "赵六", 19, true, "2023-6-27 20:10:00");
dt.Rows.Add(5, "钱七", 20, false, "2023-5-27 20:10:00");
dt.Rows.Add(6, "孙八", 21, false, "2023-4-27 20:10:00");
return dt;
}
private static void Main(string[] args)
{
DataTable dt = GetDataTable();
PrintDataTable(dt, "打印Student表");
Console.ReadKey();
}
打印Student表
|Id |Name |Age |Gender |CreateTime
--------------------------------------------------------------------------------------------------------
|1 |'张三' |17 |False |2023-09-27 20:10:00
|2 |李四 |18 |True |2023-08-27 20:10:00
|3 |王五 |19 |False |2023-07-27 20:10:00
|4 |赵六 |19 |True |2023-06-27 20:10:00
|5 |钱七 |20 |False |2023-05-27 20:10:00
|6 |孙八 |21 |False |2023-04-27 20:10:00