C# 如何在控制台应用程序中将列表打印为表格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10160770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print List as table in console application?
提问by Anas Jaber
I need Method to print List as table in console application and preview in convenient format like this:
我需要 Method 在控制台应用程序中将 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
采纳答案by Henk Holterman
Your main tool would be
你的主要工具是
Console.WriteLine("{0,5} {1,10} {2,-10}", s1, s2, s3);
The ,5and ,10are width specifiers. Use a negative value to left-align.
的,5和,10是宽度说明。使用负值左对齐。
Formatting is also possible:
格式化也是可能的:
Console.WriteLine("y = {0,12:#,##0.00}", y);
Or a Date with a width of 24 and custom formatting:
或者一个宽度为 24 和自定义格式的日期:
String.Format("Now = {0,24:dd HH:mm:ss}", DateTime.Now);
Edit, for C#6
编辑,用于 C#6
With string interpolation you can now also write
使用字符串插值,您现在还可以编写
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}" );
You don't need to call String.Format()explicitly:
您不需要String.Format()显式调用:
string s = $"Now = {DateTime.Now,24:dd HH:mm:ss}" + " " + $"y = {y,12:#,##0.00}" ;
回答by Gwyn Howell
Use \t to put in tabs to separate the columns
使用 \t 放入制表符以分隔列
回答by Nikita Ignatov
The easiest this you can do is to use an existing library
最简单的方法是使用现有的库
Install-Package ConsoleTables
And then you can define your table like so:
然后你可以像这样定义你的表:
ConsoleTable.From<Order>(orders).Write();
And it will give this output
它会给这个输出
| 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 |
Or define a custom table
或者定义一个自定义表
var table = new ConsoleTable("one", "two", "three");
table.AddRow(1, 2, 3)
.AddRow("this line should be longer", "yes it is", "oh");
table.Write();
For further examples checkout c# console table
有关更多示例,请查看c# 控制台表

