Problem with accentuation when exporting data from Sql Server to Excel

Asked

Viewed 636 times

0

I have the following code inside a button responsible for performing the export of data from my table to excel.

    string caminho = "c:\\caminho";

        // criar um arquivo para escrever

        using (StreamWriter sw = File.CreateText(caminho))

        {
            string conn = @"Server=server;Database=base;Trusted_Connection=True;";

            SqlConnection cn = new SqlConnection(conn);               

            string sql = " Select * from CLIENTE";

            SqlCommand cmd = new SqlCommand(sql, cn);

            try

            {

                //abre a conexão e gera o datareader

                cn.Open();

                SqlDataReader dr = cmd.ExecuteReader();

                // percorre o datareader e escreve os dados no arquivo .xls definido

                while (dr.Read())

                {

                    sw.WriteLine(dr["NOME"].ToString() + "\t" + dr["ENDERECO"].ToString() + "\t" + dr["CEP"].ToString() + "\t" + dr["BAIRRO"].ToString() + "\t" + dr["CIDADE"].ToString() + "\t" + dr["UF"].ToString() + "\t" + dr["TELEFONE"].ToString());

                }

                //exibe mensagem ao usuario

                MessageBox.Show("Arquivo " + caminho + " gerado com sucesso.");

            }

            catch (Exception excpt)

            {

                MessageBox.Show(excpt.Message);

            }

        } 

The data is being exported normally, the problem is that the words that contain special characters are coming uncoupled, I believe it is some configuration of Encoding but I don’t know where to do it. Someone can help me?

  • Jorge, you can use a function in SQL-SERVER to remove accents or special characters in the fields you consider a problem. Take a look at the link below and see if it suits you. https://www.dirceuresende.com/blog/how-remover-accentuaca-e-caracteres-especiais-de-umastring-no-sql-server/

  • Jorge, one option would be to insert a globalization on the application. I suggest you read this link. I’ll come up with a solution that might help you

  • using (TextWriter tw = new StreamWriter(path,append, Encoding.Default)) https://docs.microsoft.com/pt-br/dotnet/api/system.io.streamwriter.-ctor?view=netframework-4.8#System_IO_StreamWriter__ctor_System_String_System_Boolean_System_Text_Encoding_

1 answer

0

I believe this can help you.

In your App.Config (in case you are a winforms), enter the following tag inside the Configuration:

<configuration> <system.web> <globalization uiCulture="pt-BR" culture="pt-BR" enableClientBasedCulture="true" /> </system.web> </configuration>

Follows the link for a better understanding of this solution and more information on Culture Info

Browser other questions tagged

You are not signed in. Login or sign up in order to post.