简体   繁体   中英

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. The code from this link ( Export SQL Server Data into CSV file ) is working with some except. 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. If the CSV content has , inside it, then the generated CSV might be having an issue.
while (reader.Read())
{
    reader.GetValues(output);
    sw.WriteLine(string.Join(",", $"\"{output}\""));
}
  1. You can think of using library like CSVHelper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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