Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing csv file in asp.net

I'm trying to export data to a csv file, as there are chinese characters in the data i had to use unicode.. but after adding the preamble for unicode, the commas are not recognized as delimiters and all data are now written to the first column. I'm not sure what is wrong. Below is my code which i wrote in a .ashx file.

    DataView priceQuery = (DataView)context.Session["priceQuery"];
    String fundName = priceQuery.Table.Rows[0][0].ToString().Trim().Replace(' ', '_');

    context.Response.Clear();
    context.Response.ClearContent();
    context.Response.ClearHeaders();

    context.Response.ContentType = "text/csv";
    context.Response.ContentEncoding = System.Text.Encoding.Unicode;        
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fundName + ".csv");
    context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());                

    String output = fundName + "\n";        
    output += "Price, Date" + "\n";

    foreach (DataRow row in priceQuery.Table.Rows)
    {
        string price = row[2].ToString();
        string date = ((DateTime)row[1]).ToString("dd-MMM-yy");

        output += price + "," + date + "\n";
    }

    context.Response.Write(output);
like image 758
Keith Avatar asked Feb 15 '11 06:02

Keith


1 Answers

Looks like MS Office does not support Unicode csv files.

But some users reported that tab delimiter works.

I would try UTF-8 rather than Unicode, this can cause delimiters treated as ASCII characters.

like image 65
Artem Koshelev Avatar answered Oct 14 '22 06:10

Artem Koshelev