导出编码正确的文件



我不明白这里缺少了什么。我试图导出一个csv格式的文件,扩展ASCII字符,如ÿü,但我得到的全部是"
我需要在响应中指定其他内容吗?

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();

我认为您应该添加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();

遗憾的是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();

我是一个Java程序员,你确定你需要一个StreamReader吗?我猜StreamReader(stream)可能会解码字节在不同的字符集。而且,你已经有了字节,也许你可以直接写入字节来响应。

相关内容

  • 没有找到相关文章

最新更新