导出具有正确编码的文件

时间:2011-04-08 03:38:18

标签: c# encoding file httpresponse

我不明白这里缺少什么。我正在尝试使用ASCIIÿ这样的扩展ü字符导出csv格式的文件,但我得到的是
我是否需要在响应中指定其他内容?

Encoding encoding = Encoding.UTF8;

//ToCSV writes the string correctly
var bytes = encoding.GetBytes("write ÿ or ü please");
MemoryStream stream = new MemoryStream(bytes);

StreamReader reader = new StreamReader(stream);
//TextWriter tw = new TextWriter();
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
Response.Charset = encoding.EncodingName;
Response.ContentType = "application/text";
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();

3 个答案:

答案 0 :(得分:20)

我相信您应该添加Response.ContentEncoding = Encoding.Unicode以获得正确的输出。

    Encoding encoding = Encoding.UTF8;
    var bytes = encoding.GetBytes("write ÿ or ü please");
    MemoryStream stream = new MemoryStream(bytes);
    StreamReader reader = new StreamReader(stream);
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename"));
    Response.Charset = encoding.EncodingName;
    Response.ContentType = "application/text";
    Response.ContentEncoding = Encoding.Unicode;
    Response.Output.Write(reader.ReadToEnd());
    Response.Flush();
    Response.End();

答案 1 :(得分:5)

不幸的是Encoding.Unicode无效,使用Windows-1252工作:

Response.Clear();
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"filename.csv\"");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Write(string.Join(Environment.NewLine, myDataLines));
Response.End();

答案 2 :(得分:0)

我是Java程序员,您确定需要StreamReader吗?我猜StreamReader(stream)可能会解码不同字符集中的字节。并且,您已经获得了字节,也许您可​​以直接将字节写入响应。