我需要方法在控制台应用程序中将List打印为表格并以方便的格式预览,如下所示:
Pom_No Item_Code ordered_qty received_qty
1011 Item_Code1 ordered_qty1 received_qty1
1011 Item_Code2 ordered_qty2 received_qty2
1011 Item_Code3 ordered_qty3 received_qty3
1012 Item_Code1 ordered_qty1 received_qty1
1012 Item_Code2 ordered_qty2 received_qty2
1012 Item_Code3 ordered_qty3 received_qty3
答案 0 :(得分:38)
您的主要工具是
Console.WriteLine("{0,5} {1,10} {2,-10}", s1, s2, s3);
,5
和,10
是宽度说明符。使用负值进行左对齐。
也可以格式化:
Console.WriteLine("y = {0,12:#,##0.00}", y);
或宽度为24的日期和自定义格式:
String.Format("Now = {0,24:dd HH:mm:ss}", DateTime.Now);
使用字符串插值,您现在也可以编写
Console.WriteLine($"{s1,5} {s2,10} {s3,-10}");
Console.WriteLine($"y = {y,12:#,##0.00}");
String.Format($"Now = {DateTime.Now,24:dd HH:mm:ss}" );
您无需明确致电String.Format()
:
string s = $"Now = {DateTime.Now,24:dd HH:mm:ss}" + " " + $"y = {y,12:#,##0.00}" ;
答案 1 :(得分:22)
最简单的方法是使用existing library
Install-Package ConsoleTables
然后你可以这样定义你的表:
ConsoleTable.From<Order>(orders).Write();
它将提供此输出
| Id | Quantity | Name | Date |
|----------|----------|-------------------|---------------------|
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
| 3355 | 6 | Some Product 3355 | 18-04-2016 00:52:52 |
或定义自定义表格
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
table.Write();
有关结帐c# console table
的更多示例答案 2 :(得分:2)
使用\ t设置标签以分隔列