3

我在将数据导出到 .csv 文件时遇到问题。我使用2种方法。

        Encoding csvEncoding = new UTF8SignatureEncoding();
        byte[] csvFile = TestByte(CsvContentDelimiter.NewLine, CsvContentDelimiter.Semicolon, csvEncoding);


        string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "text/csv";
        Response.ContentEncoding = csvEncoding;
        Response.AppendHeader("Content-Disposition", attachment);
        Response.BinaryWrite(csvFile);
        Response.Flush();
        Response.End();

    public byte[] TestByte(CsvContentDelimiter rowDelimiter, CsvContentDelimiter columnDelimiter, Encoding encoding)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("product;");
        return encoding.GetBytes(sb.ToString());
    }

此代码创建 .csv 文件,但文件编码错误,我只看到一些“哈希”

4

1 回答 1

2

这是一个使用 UTF8 格式的完整示例。它使用您自己的代码,因此表明是您的编码导致了问题:

namespace WebApplication1
{
    using System;
    using System.Text;

    public partial class _Default : System.Web.UI.Page
    {
        protected void btnExport_Click(object sender, EventArgs e)
        {
            // Use UTF8 encoding
            Encoding csvEncoding = Encoding.UTF8;
            byte[] csvFile = TestByte(csvEncoding);

            string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "text/csv";
            Response.ContentEncoding = csvEncoding;
            Response.AppendHeader("Content-Disposition", attachment);
            Response.BinaryWrite(csvFile);
            Response.Flush();
            Response.End();
        }

        public byte[] TestByte(Encoding encoding)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Record1,Fred,Bloggs,26{0}", Environment.NewLine);
            sb.AppendFormat("Record2,John,Smith,32{0}", Environment.NewLine);
            return encoding.GetBytes(sb.ToString());
        }
    }
}
于 2012-12-12T13:08:31.530 回答