Synapsido
Synapsido

Reputation: 140

CSV file export with encoding issues

I'm trying to export a SQL Server table into a CSV file:

Data in the table is like = Presentación or Difusión

All is working good... but in the .CSV file I find:

Presentación or Difusión

This is my .cs code:

GridView1.AllowPaging = false;
GridView1.DataBind();

StringBuilder sb = new StringBuilder();

for (int k = 0; k < GridView1.Columns.Count; k++)
{
    // add separator
    sb.Append(GridView1.Columns[k].HeaderText + ';');
}

// append new line
sb.Append("\r\n");

for (int i = 0; i < GridView1.Rows.Count; i++)
{
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        // add separator
        sb.Append(GridView1.Rows[i].Cells[k].Text + ';');
    }

    // append new line
    sb.Append("\r\n");
}

Encoding encoding = Encoding.UTF8;

Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=OrigenDatos.csv");  
Response.Charset = encoding.EncodingName;
Response.ContentType = "application/text";
Response.ContentEncoding = Encoding.Unicode;
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();

Is UTF-8 the true charset?

Upvotes: 1

Views: 5332

Answers (2)

nisan
nisan

Reputation: 37

You can try out this below code

        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, Encoding.UTF8) + "");
        Response.Cookies.Add(new System.Web.HttpCookie("fileDownload", "true"));
        Response.Charset = "";
        Response.ContentType = "application/csv";
        Response.ContentEncoding = Encoding.UTF8;
        Response.BinaryWrite(Encoding.UTF8.GetPreamble());
        Response.Write(outPutStringData); // Information which you want in .csv file
        Response.Flush();
        Response.End();

Upvotes: 0

vlad.rad
vlad.rad

Reputation: 1083

In order to correctly decode an HTML file, your browser needs to know which encoding to use. You can tell it to him by setting the charset parameter or by setting meta tag: <meta charset="UTF-8">

So: you need to save the HTML file using UTF-8 and declare that encoding properly.

It can also theoretically be that on your server default encoding is other as UTF-8 - then you should delete the AddDefaultCharset your_encoding from the .htaccess server file and write AddDefaultCharset utf-8. But I am not sure that this is about your case.

EDIT:

The byte &#243; stands for Spanish character ó in UTF-8. So I think you should not try to encode with other encodings, because it is definitely utf-8.

Upvotes: 2

Related Questions