Tuyen Nguyen
Tuyen Nguyen

Reputation: 4479

ASP.NET C# export data into CSV format, double quotes not preserved

I'm trying to export some data to CSV with ASP.NET C#.
I use this code:

private void writeCSVfile(DataTable theData, string fileName)
{
     StringBuilder dataString = new StringBuilder();
     string currentId = Guid.Empty.ToString();
     HttpContext context = HttpContext.Current;
     context.Response.Clear();

     foreach (DataColumn column in GTDSSearchData.Columns)
     {
        if (column.ColumnName.ToString().ToLower() != "the_id")
        {
            dataString.Append(column.ColumnName + ",");
        }
     }
     dataString.Remove(dataString.Length - 1, 1);
     dataString.Append(Environment.NewLine);

     foreach (DataRow row in GTDSSearchData.Rows)
     {
        currentId = row[1].ToString();
        for (int i = 1; i < GTDSSearchData.Columns.Count; i++)
        {
            dataString.Append(row[i].ToString().Replace(",", string.Empty) + ",");
        }
        dataString.Remove(dataString.Length - 1, 1);
        dataString.Append(Environment.NewLine);
    }

    context.Response.Write(dataString.ToString());
    context.Response.ContentType = "text/csv";
    context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
    context.Response.End();
}

My dataString is

test1, 1  
"hello world", 10  
test2, 2

The result CSV file has these content

test1, 1  
hello world, 10  
test2, 2

Do you know why my double quotes go away and how to preserve them when exporting to CSV file.

Thanks a lot.

Upvotes: 1

Views: 9010

Answers (2)

akmed0zmey
akmed0zmey

Reputation: 573

Use escape sequences, for example \" - double quote. This can help you https://stackoverflow.com/a/323670/1600531

Upvotes: 0

Icarus
Icarus

Reputation: 63956

You need to enclose each quotation mark in double quotes. In other words, you need to make your program write this:

test1, 1  
"""hello world""", 10  
test2, 2

And then it will preserve the double quotes

Upvotes: 2

Related Questions