0

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();
}

1 Answers1

0

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58