Convert SQL Result to CSV File

I am working in C # and need to use Entity Framework 6 . I have a service that calls a stored procedure (using Dbcontext) and puts the results in an IList . Then I have a controller that uses this service. Now initially I used the results in combination with Epplus to save this as an Excel / Xlsl file - this worked fine / as intended.

However, now I need to save it as a CSV file. I found a few links like this and this which converts excel to CSV (however I can skip this step now, since I can just convert the result set to CSV, no need for an excel file), I also found this link .

From what I understand it is pretty easy to export / convert dataset / result to CSV using a string constructor . However, I was wondering, considering I have Epplus , and the ability to save to Excel is not the best way to do it ? Or is it better to take the data, use a string constructor for the comma separating the values, and use that for the CSV?

I know similar threads ( like this one ) before, but I felt like my question was unique enough for a new post.

+3


source to share


1 answer


Using EPPlus is not a cleaner way to do this. You will need a lot more code to achieve exactly the same result. Creating a CSV file is nothing more than writing a text file with commas. So why not just do it?



StringBuilder sb = new StringBuilder();
foreach (DataRow dr in yourDataSet) 
{
  List<string> fields = new List<string>();
  foreach (object field in dr.ItemArray) 
  {
     fields.Add(field);
  }
  sb.Append(String.Join(",", fields) + Environment.NewLine);
}

//and save.. sb.ToString() as a .csv file

      

-1


source







All Articles