Export flat file with special characters in C #

1

I have a query from SQL , I show it in a GridView in a web page ( ASP.NET ) and from there I export it to a flat file delimited with C # and I have problems with accents and special characters.

For example, the word MUÑOZ , that the Ñ must occupy a space, I get MUÑOZ and it overflows the delimitation of the file.

protected void btnGenerar_Click(object sender, EventArgs e)
{

    string nombre = "Archivo" + DateTime.Now.ToShortDateString();
    //Encoding encoding = Encoding.UTF8;

     Response.Clear();
     Response.ContentEncoding = System.Text.Encoding.UTF8;

        Response.Buffer = true;
        Response.AddHeader("content-disposition",
         "attachment;filename="+nombre+".txt");
        Response.Charset = "";
        Response.ContentType = "application/text";
         gvDatos.AllowPaging = false;
         gvDatos.DataBind();

        StringBuilder sb = new StringBuilder();

     //añadimos la cabecera desde el texbox

            string cab = txtCabecera.Text;

            sb.Append(cab);

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

        CargarDatos();

        for (int i = 0; i < gvDatos.Rows.Count; i++)
        {
            for (int k = 0; k < gvDatos.Columns.Count; k++)
            {
                //add separator
                sb.Append(gvDatos.Rows[i].Cells[k].Text);
            }
            //append new line
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();
}
    
asked by Freddy Poma Inga 07.07.2017 в 00:49
source

2 answers

0

I solved it by changing the property of the BoundField of the Gridview HtmlEncode from true to false. <asp:BoundField DataField="contribuyente" HeaderText="CONTRIBUYENTE" HtmlEncode="False" />

    
answered by 07.07.2017 / 23:50
source
1

This owes to the encoding . You should use utf-8 which is the standard encoding.

Here:

Response.Charset = "";

It should be:

Response.Charset = "utf-8";

You also add this tag below head just in case:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
 ...
</html>
    
answered by 07.07.2017 в 19:51