有时候我们需要在控制台中打印DataTable,这里提供一个自己写的简单函数给他人做参考,如果有任何意见建议,不吝赐教。
实际输出如图:
1 /// <summary> 2 /// Print a DataTable on to the console 3 /// </summary> 4 /// <param name="table">the table to be printed</param> 5 public static void PrintTable(DataTable table) 6 { 7 // print head 8 PrintLine(12 * table.Columns.Count); 9 foreach (DataColumn col in table.Columns) 10 { 11 Console.Write(string.Format("{0,12}",col.Caption)); 12 } 13 Console.Write("\n"); 14 PrintLine(12 * table.Columns.Count); 15 16 // print rows 17 for (int i = 0; i < table.Rows.Count; i++) 18 { 19 for (int j = 0; j < table.Columns.Count; j++) 20 { 21 Console.Write(string.Format("{0,12}",table.Rows[i][j].ToString())); 22 } 23 Console.Write("\n"); 24 } 25 PrintLine(12 * table.Columns.Count,"-"); 26 } 27 28 /// <summary> 29 /// Print a line with specific char on to the console 30 /// </summary> 31 /// <param name="length">count of the char to be printed</param> 32 /// <param name="lineChar">the char to be printed, default is "="</param> 33 private static void PrintLine(int length, string lineChar = "=") 34 { 35 string line = string.Empty; 36 for (int i = 0; i < length; i++) 37 { 38 line += lineChar; 39 } 40 Console.WriteLine(line); 41 }