1

我正在将表的数据从 SQL Server 导出到文本文件。

我想在除最后一列(标题+数据)之外的每一列之后附加一个分隔符,但我编写的代码也在最后一列之后添加了一个分隔符。

我该如何预防?

public static void export_to_txt()
{
    SqlDataReader reader;

    string query = "Select * from tablename";
    string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string strDelimiter = "\t";
    string strFilePath = @"mypath";

    StringBuilder sb = new StringBuilder();

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();

        using (reader = new SqlCommand(query, conn).ExecuteReader())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                sb.Append(reader.GetName(i));
                sb.Append(strDelimiter);
            }

            sb.Append(Environment.NewLine);

            if (reader.HasRows)
            {
                Object[] items = new Object[reader.FieldCount];

                while (reader.Read())
                {
                    reader.GetValues(items);

                    foreach (var item in items)
                    {
                        sb.Append(item.ToString());
                        sb.Append(strDelimiter);
                    }

                    sb.Append(Environment.NewLine);
                }
            }
        }

        conn.Close();
        File.WriteAllText(strFilePath, sb.ToString());
    }
}
4

3 回答 3

3

改为使用string.Join

 sb.Append(string.Join(strDelimiter, items));

对于标题行,您可以将其读入列表或使用 LINQ:

var headers = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i));

然后使用string.Join.

于 2016-03-10T20:10:46.913 回答
1

您需要修改此代码:

for (int i = 0; i < reader.FieldCount; i++)
{
    sb.Append(reader.GetName(i));
    sb.Append(strDelimiter);
}

for (int i = 0; i < reader.FieldCount; i++)
{
    sb.Append(reader.GetName(i));
    if (i == reader.FieldCount - 1)
        continue;
    sb.Append(strDelimiter);
}
于 2016-03-10T20:27:48.577 回答
1
using (reader = new SqlCommand(query, conn).ExecuteReader())
{
     for (int i = 0; i < reader.FieldCount; i++)
     {
           sb.Append(reader.GetName(i));
           if( i < (reader.FieldCount -1)
               sb.Append(strDelimiter);
     }
     sb.Append(Environment.NewLine);
     if (reader.HasRows)
     {
          Object[] items = new Object[reader.FieldCount];

          while (reader.Read())
          {
                reader.GetValues(items);
                sb.Append(string.Join(strDelimiter,item.ToString()));
                sb.Append(Environment.NewLine);
          }
      }
 }
于 2016-03-10T20:34:42.767 回答