Writing csv file in asp.net
Asked Answered
D

1

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);
Duffy answered 15/2, 2011 at 6:43 Comment(2)
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.Ambuscade
Any feedback is welcomed. I'll take note of that and change it accordinglyDuffy
T
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.

Trombley answered 15/2, 2011 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.