在ASP.NET中编写CSV文件

6
我正在尝试将数据导出到CSV文件中,由于数据中有中文字符,所以我必须使用Unicode。但是,在添加Unicode前言后,逗号不被识别为分隔符,所有数据现在都写入了第一列。我不确定问题出在哪里。以下是我在.ashx文件中编写的代码。
    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);

我知道这不是你问题的一部分,但你不应该使用 output += price + ... 而应该使用 StringBuilder 对象。每次像这样连接字符串时,整个新字符串都会被重新分配。请记住,在C#中,字符串是不可变对象。 - Brettski
欢迎提供任何反馈意见。我会注意并相应地进行更改。 - Keith
1个回答

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接