Question

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);
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top