6

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);
Keith
  • 63
  • 1
  • 5
  • I know this isn't part of your question but you should not use output += price + ... use a StringBuilder object instead. Each time you concatenate a string like that the entire new string is reallocated. Remember strings in C# are immutable objects. – Brettski Feb 15 '11 at 06:47
  • Any feedback is welcomed. I'll take note of that and change it accordingly – Keith Feb 15 '11 at 06:55

1 Answers1

4

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.

Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68