简体   繁体   中英

Export to .csv File

I had problem with export data to .csv file. I use 2 methods.

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

And

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

This code create .csv file, but file have bad Encoding and i see only some "hash"

Here is a fully working example using UTF8 formatting. It uses your own code so shows that it is your Encoding that is causing the issue:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM