String.Format方法,用于在文本文件中对齐数据库输出

时间:2019-04-12 08:58:07

标签: c# database string text-files string.format

我知道还有其他一些与我的问题有关的问题,但它们仍然对我没有太大帮助。我试图理解String.Format方法的概念,但是我一遍又一遍地失败,仍然不知道如何在我的情况下使用它。我知道它被问到很多,但是如果有人对如何使对齐方式有所了解,我将不胜感激。

我将不同数据库表的输出保存到不同的文本文件。我想将列的“名称”与其“值”对齐。这非常有意义,因为在某些表中有很多“空”值,这会导致输出格式不正确。因为“空”不会导出到该文件,因此值将移到左侧。

Database Table vs. Text File

private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile)
{
    string pathOfOutputFile = dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile;           

    using (SqlConnection sqlCon = new SqlConnection("Data Source=" + 
    GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
    {
        SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, sqlCon);     
        try
        {
          sqlCon.Open();
          DataSet dataset = new DataSet();
          adapter.Fill(dataset, "nameOfDataset");
          string currentLine = "";
          foreach (var col in dataset.Tables[0].Columns)
          {
            currentLine += " " + col.ToString();
          }

         OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);

         foreach (DataRow row in dataset.Tables[0].Rows)
         {
            currentLine = "";
            foreach (var item in row.ItemArray)
            {
                currentLine += " " + item.ToString();
            }
            OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
          }
     }
     catch (Exception ex)
     {
        logger.Debug(ex, "Writing Database Output to the " + "\"" + nameOfOutputFile + "\"" + " file failed");
     }
     finally
     {
        sqlCon.Close();
     }
   }
}

2 个答案:

答案 0 :(得分:1)

如果事先知道所需的格式,那么

string.Format是好的,如果您拥有诸如查询结果之类的动态源,则

string.Format就不好。尝试这样的事情:

private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile)
{
    string pathOfOutputFile = dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile;           

    using (SqlConnection sqlCon = new SqlConnection("Data Source=" + 
    GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
    {
        SqlDataAdapter adapter = new SqlDataAdapter(sqlQuery, sqlCon);     
        try
        {
          sqlCon.Open();
          DataSet dataset = new DataSet();
          adapter.Fill(dataset, "nameOfDataset");
          string currentLine = "";
          var nameLengths = new int[dataset.Tables[0].Columns.Count];
          var i = 0;
          foreach (var col in dataset.Tables[0].Columns)
          {
            var colName = col.ToString();
            nameLengths[i] = colName.Length;
            currentLine += " " + colName;
            i++;
          }

         OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);

         foreach (DataRow row in dataset.Tables[0].Rows)
         {
            currentLine = "";
            i = 0;
            foreach (var item in row.ItemArray)
            {
                var field = item.ToString();
                currentLine += " " + field.PadRight(nameLengths[i], ' ');
                i++;
            }
            OutputHandler.AppendDataToFile(pathOfOutputFile, currentLine);
          }
     }
     catch (Exception ex)
     {
        logger.Debug(ex, "Writing Database Output to the " + "\"" + nameOfOutputFile + "\"" + " file failed");
     }
     finally
     {
        sqlCon.Close();
     }
   }
}

答案 1 :(得分:0)

如果获得每个列名和数据值的字符串表示形式的长度,则可以计算出每列的最小宽度,并为该列准备一个格式字符串,以设置其最小宽度。

类似这样的东西:

using System;
using System.Data;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable dt = SampleData();

            // Prepare the column formats
            int nCols = dt.Columns.Count;
            var dataWidths = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName.Length).ToList();

            foreach (DataRow d in dt.Rows)
            {
                for (int i = 0; i < nCols; i++)
                {
                    dataWidths[i] = Math.Max(dataWidths[i], d.ItemArray[i].ToString().Length);
                }
            }

            var colFormats = dataWidths.Select(x => $"{{0,{-x}}}").ToList();

            //

            var sb = new StringBuilder();

            // Add the column names
            sb.AppendLine(string.Join(" ", dt.Columns.Cast<DataColumn>().Select((x, i) => string.Format(colFormats[i], x.ColumnName))));

            // Add in the data
            foreach (DataRow d in dt.Rows)
            {
                sb.AppendLine(string.Join(" ", d.ItemArray.Select((x, i) => string.Format(colFormats[i], x))));
            }

            Console.WriteLine(sb.ToString());

            Console.ReadLine();


        }

        static DataTable SampleData()
        {

            DataTable sdt = new DataTable();
            string[] cn = "ARCHIVE DBDATETIME NEXTDOCID HIGHESTDISK SYSTEMTYPE FLAGS VERSION SINGLEUSER".Split(' ');

            foreach (string n in cn)
            {
                sdt.Columns.Add(n);
            }

            DataRow drn = sdt.NewRow();
            drn["ARCHIVE"] = "Hello";
            drn["DBDATETIME"] = 1316859;
            drn["NEXTDOCID"] = 1;
            drn["HIGHESTDISK"] = "Nothing";
            drn["SYSTEMTYPE"] = 1;
            drn["FLAGS"] = "ABC";
            drn["VERSION"] = "Hello";
            drn["SINGLEUSER"] = 256;
            sdt.Rows.Add(drn);

            drn = sdt.NewRow();
            drn["ARCHIVE"] = "Value longer than header";
            // No value for drn["DBDATETIME"] etc.
            drn["SINGLEUSER"] = 256;
            sdt.Rows.Add(drn);

            return sdt;
        }

    }
}

示例输出:

ARCHIVE                  DBDATETIME NEXTDOCID HIGHESTDISK SYSTEMTYPE FLAGS VERSION SINGLEUSER
Hello                    1316859    1         Nothing     1          ABC   Hello   256
Value longer than header                                                           256