【问题标题】:Formatting displayed data (properly) in console window from在控制台窗口中(正确)格式化显示的数据
【发布时间】:2020-01-06 15:52:43
【问题描述】:

我正在学习在控制台窗口中显示来自 Sql 数据库的数据库中的数据,连接已建立,问题在于我的显示数据不统一/整齐。有没有办法解决这个问题。

代码*

                {
                    Console.WriteLine("FirstColumn\tSecond Column\t\tThird Column\t\tForth Column\t");
                    while (reader.Read())
                    {

                        Console.WriteLine(String.Format("{0} \t | {1} \t\t | {2} \t | {3} \t | {4} \t | ",
                            reader[0], reader[1], reader[2], reader[3], reader[4], reader[5]));
                    }
                } 

我希望数据显示对齐且整齐。 提前致谢

【问题讨论】:

    标签: c# sql visual-studio


    【解决方案1】:

    没有尝试,但这应该有点工作。它是在右边用空格填充 reader[0],达到指定的总长度。

    int totalLength = 50;
    Console.WriteLine(reader[0].PadRight(totalLength) + String.Format(" \t | {1} \t\t | {2} \t | {3} \t | {4} \t | ", reader[1], reader[2], reader[3], reader[4], reader[5]));
    

    【讨论】:

      【解决方案2】:

      正如您所做的那样,表格可用于正确对齐列。但是如果单元格的内容太大,对齐就会中断,即下面的示例中值second将列推得太远:

      C1    | C2
      first | a
      second    | b
      third | b
      

      此外,您无法控制一个选项卡有多少个空格。这是一个用户设置。它可以是 2、4、8 或其他任何值。

      另一种解决方案是使用填充来控制每列的​​确切字符数(包括空格)。但是如果一个单元格内容太大,也会出现同样的问题。

      因此,正确的解决方案是使用带省略号的填充,例如 text-overflow: ellipsis; 进行 HTML/CSS 渲染。

      假设你所有的列宽都是 10 个字符,如果它太大,你需要“剪切”单元格内容值,如示例:

      C1        | C2
      long      | a
      verylong  | b
      veryvery..| b
      

      【讨论】:

        【解决方案3】:

        您可以使用填充来正确对齐输出。

        找出你想要的每一列的宽度,然后相应地填充字符串:

        var value = "Sample";
        
        //Desired length
        var length = 20;
        
        //Trim strings longer than the desired length
        value = (value.Length > length) ? $"{value.Substring(0,20)}..." : value;
        
        //Pad to always have the same length
        var paddedValue = value.PadRight(length, ' ');
        

        在上面的示例中,paddedValue 将包含一个以 Sample 开头的字符串和 14 个额外的空格。

        您可以阅读有关字符串填充的更多信息here

        这是一个简单的示例,但您应该清楚,您可以将其封装到可重用的函数/类中。

        这是一个使用数组来说明的示例实现。您可以创建一个负责修剪/填充字符串的函数:

        private static string GetFormattedValue(string value, int maxLength)
        {
            //Trim strings longer than the desired length
            var output = (value.Length > maxLength) ? $"{value.Substring(0, 20)}..." : value;
            //Pad to always have the same length
            var paddedValue = output.PadRight(maxLength, ' ');
            return paddedValue;
        }
        

        以下是一些示例定义和数据:

        var lengths = new[] { 20, 30, 10 }; 
        var headers = new[] { "Title", "Description Header that is also too long", "Quantity" };
        var values = new[] {"Small text", "Super long text that will not fit", "15" };
        

        使用 Linq 为 标头和值生成字符串(标头也可能太长!):

        var headerString = string.Join("|", headers.Select((h, i) => GetFormattedValue(h, lengths[i])));
        Console.WriteLine(headerString);
        var valueString = string.Join("|", values.Select((v, i) => GetFormattedValue(v, lengths[i])));
        Console.WriteLine(valueString);
        

        输出:

        【讨论】:

          【解决方案4】:

          你可以试试下面的代码,使用一个打包的类来显示数据的格式 表。

           class Program
          {
              static void Main(string[] args)
              {
                  var t = new TablePrinter("Id", "Name", "Age");
                  string connectionstring = "connectionstring";
                  SqlConnection connection = new SqlConnection(connectionstring);
                  connection.Open();
                  string sql = "Select * from Student";
                  SqlCommand command = new SqlCommand(sql,connection);
                  SqlDataReader reader = command.ExecuteReader();
                  while(reader.Read())
                  {
                      t.AddRow(reader["Id"], reader["Name"], reader["Age"]);
                  }
          
                  t.Print();
                  Console.ReadKey();
              }
          }
          
          public class TablePrinter
          {
              private readonly string[] titles;
              private readonly List<int> lengths;
              private readonly List<string[]> rows = new List<string[]>();
          
              public TablePrinter(params string[] titles)
              {
                  this.titles = titles;
                  lengths = titles.Select(t => t.Length).ToList();
              }
          
              public void AddRow(params object[] row)
              {
                  if (row.Length != titles.Length)
                  {
                      throw new System.Exception($"Added row length [{row.Length}] is not equal to title row length [{titles.Length}]");
                  }
                  rows.Add(row.Select(o => o.ToString()).ToArray());
                  for (int i = 0; i < titles.Length; i++)
                  {
                      if (rows.Last()[i].Length > lengths[i])
                      {
                          lengths[i] = rows.Last()[i].Length;
                      }
                  }
              }
          
              public void Print()
              {
                  lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
                  System.Console.WriteLine("+");
          
                  string line = "";
                  for (int i = 0; i < titles.Length; i++)
                  {
                      line += "| " + titles[i].PadRight(lengths[i]) + ' ';
                  }
                  System.Console.WriteLine(line + "|");
          
                  lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
                  System.Console.WriteLine("+");
          
                  foreach (var row in rows)
                  {
                      line = "";
                      for (int i = 0; i < row.Length; i++)
                      {
                          if (int.TryParse(row[i], out int n))
                          {
                              line += "| " + row[i].PadLeft(lengths[i]) + ' ';  // numbers are padded to the left
                          }
                          else
                          {
                              line += "| " + row[i].PadRight(lengths[i]) + ' ';
                          }
                      }
                      System.Console.WriteLine(line + "|");
                  }
          
                  lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
                  System.Console.WriteLine("+");
              }
          }
          

          示例结果:

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-10
            • 2021-02-11
            • 2010-09-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-04
            相关资源
            最近更新 更多