How to convert from Text to Number via code to EXCEL in C #

5

I have a program that reads data from a text file and exports it to an excel report.

I have a problem with transcription of numbers, in the txt file I have data in this format:

8,000000

This value should be regarded as 8 (number) by the report, so I made a routine to remove this "000000" and it works, here is the code

//trim porquê o número vem com alguns espaços 
string content = itensCarac[indexColumnText].Replace(",000000", "").Trim();
planConfig.Cells[indexLine, indexColumn++] = content;

It turns out there are numbers in the report in this format:

4.700,000000

In theory the same logic would work. but Excel views that number as "4.7" (You know why), it "turned" the point into a comma and killed the 00.

If I do not apply this logic to the lines where it has a floating point, excel treats them as text, and converting excel to number solves the problem. As the image below shows

Here'sthequestion:

Howtomakethistext-to-numberconversionviacodetherightway?

NOTE:

I'vealreadytriedusing

NumberFormat="0.0";

or the

NumberFormat = "0";

and the results were "4.7"

    
asked by anonymous 03.06.2016 / 19:56

3 answers

3

Use Double.Parse with CultureInfo("pt-br") , if you always have numbers in this column. Or Double.TryParse if you're not sure if a number will always come in this column.

In your case, your code can look like this, nor do you need trim or replace:

string content = Double.Parse(itensCarac[indexColumnText], cultura);
planConfig.Cells[indexLine, indexColumn++] = content;

Below I made a code with the first example "8,000000" and "4,700,000000". I also added another case "4,700,100,000" and two more examples using TryParse instead of Parse.

using System;
using System.Globalization;//Para o CultureInfo

public class Program
{
    public static void Main()
    {           
        //Setei a cultura para Português Brasil.
        CultureInfo cultura = new CultureInfo("pt-br"); 

        //Teste com 8,000000
        double valor8 = Double.Parse("8,000000", cultura);
        Console.WriteLine(valor8);

        //Teste com 4.700,000000
        double valor4_7 = Double.Parse("4.700,000000", cultura);        
        Console.WriteLine(valor4_7);

        //Teste com 4.700,100000
        double valor4_7_1 = Double.Parse("4.700,100000", cultura);
        Console.WriteLine(valor4_7_1);

        //Teste com TryParse 1.230,15
        double x=0;     
        bool testeEhNumerico = Double.TryParse("1.230,15",NumberStyles.Any,cultura, out x);                     
        Console.WriteLine(x);
        Console.WriteLine(testeEhNumerico);

        //Teste com TryParse caso não venha um número 
        double y=0;     
        bool testeNaoNumerico = Double.TryParse("Não sou numérico!",NumberStyles.Any,cultura, out y);   
        Console.WriteLine(y);
        Console.WriteLine(testeNaoNumerico);

    }
}

The results are:

8
4700
4700.1
1230.15
True
0
False

See the example working with comments in link

I tried a very playful code, I hope it's clear.

    
03.06.2016 / 22:24
2

I'm not sure if it'll help, but there's something in stackoverflow in English: How can I convert String to Int? a>

Translating is something + - like this:

He tells you to try this:

int x = Int32.Parse(variável);

or, in a better way: (I believe that according to your goal it would not be interesting but good to know)

int x = 0;
Int32.TryParse(variável, out x);

Where Int32.TryParse returns a bool that can be used in an if

returns to bool you can return the value of the results of the parsing attempt:

int x = 0;

if (Int32.TryParse (TextBoxD1.Text, out x)) {     // you know that the parsing attempt     // was successful }

  

The TryParse method is like the Parse method, except the TryParse   method does not throw an exception if the conversion fails. It   eliminates the need to use exception handling to test for   FormatException in the event that is invalid and can not be   successfully parsed. - MSDN

Translating.  The TryParse method is similar to Parse, except that TryParse does not throw at any exception when the conversion fails. This eliminates the need to handle exceptions and try to figure out the formats of those exceptions when the action fails.

Remember that you also have Convert.ToInt

Convert.ToInt16(variável);
Convert.ToInt32(variável);
Convert.ToInt64(variável);

Link from the Microsoft Web site at English that tells you about Convert and Portuguese

    
03.06.2016 / 21:41
1

You should be using Excel in Portuguese , but the data is treated originally in English , thus 4,700,000000 is for Excel (as you are sending data) equal to 4.7 , because in English the symbol for separating thousands is the comma (disregarded in this case because it comes after the point) , and the period is the decimal point separator.

The suggestion is you replace the comma characters in place of a dot and vis-versa before sending to Excel , sending the example number in this way:

4,700.000000 (form in English)

Doing this will work!

If you send as text, send " = 4,700.000000 ", which Excel will treat as value if the cell is formatted for value , and it will automatically go to the Portuguese .

    
05.06.2016 / 17:11