简体   繁体   English

将 SQL 服务器数据导出为 CSV 文件在桌面数据中包含逗号

[英]Export SQL Server Data into CSV file on desktop data contain commas

I am trying to export data into a CSV file from the SQL server.我正在尝试从 SQL 服务器将数据导出到 CSV 文件中。 The code from this link ( Export SQL Server Data into CSV file ) is working with some except.此链接中的代码( 将 SQL 服务器数据导出到 CSV 文件中)正在处理一些例外。 In some rows that contain commas, the table arrangement is not correct.在某些包含逗号的行中,表格排列不正确。 The code i have try我尝试过的代码

using (var connection = ConnectionToSqlServer.GetConnection())
{
    connection.Open();

    SqlCommand sqlCmd = new SqlCommand("Select * from  dbo.Test", connection);
    SqlDataReader reader = sqlCmd.ExecuteReader();

    string fileName = "test.csv";
    StreamWriter sw = new StreamWriter(fileName);
    object[] output = new object[reader.FieldCount];

    for (int i = 0; i < reader.FieldCount; i++)
    {
         for (int i = 0; i < reader.FieldCount; i++)
         {

           if (reader.GetName(i).Contains(","))
           {
              output[i] = "\"" + reader.GetName(i) + "\"";
            }
            else
            output[i] = reader.GetName(i);
           }
    }

    sw.WriteLine(string.Join(",", output));

    while (reader.Read())
    {
        reader.GetValues(output);
        sw.WriteLine(string.Join(",", output));
    }

    sw.Close();
    reader.Close();
    connection.Close();
}

I am suggesting you consider below options:我建议您考虑以下选项:

  1. Quote the values, to have proper CSV generation.引用这些值,以获得正确的 CSV 生成。 If the CSV content has , inside it, then the generated CSV might be having an issue.如果 CSV 内容中有,则生成的 CSV 可能有问题。
while (reader.Read())
{
    reader.GetValues(output);
    sw.WriteLine(string.Join(",", $"\"{output}\""));
}
  1. You can think of using library like CSVHelper你可以考虑使用像CSVHelper这样的库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM