Search code examples
c#exceldatareader

ExcelDataReader does not read floats with comma like "123,45" (instead reads "123.45")


How can I read float values with comma like 123,45?

I have to read third party excel files that come formatted like 123,45 and I can not / am not allowed to reformat them to 123.45.

I am now using this method:

    string GetCell(int row, int col)
    {
        if (Sheet != null)
        {
            try
            {
                string cellContent = Sheet[row][col].ToString(); // careful "ToString()" syntax!
                //Print("Excel.Get({0},{1}): {2}", row, col, cellContent);
                return cellContent;
            }
            catch (Exception e)
            {
                Print("Excel.Get("+row+","+col+") error: "+ e.Message);
                return null;
            }
        }
        else
        {
            Print("Excel.Get("+ row + ","+ col+") error: sheet is null");
            return null;
        }
    }

but the string is returned as 12345.

Thanks in advance!


Solution

  • You could try to specify a culture

        string valueRead = "123,45";
        CultureInfo frenchCultureInfo = new CultureInfo("fr-FR");
        float valueParsed = float.Parse(valueRead, frenchCultureInfo);
    

    EDIT : as per your comment, you can specify the culture using the Excel interop. Other choices include, read values as string and use float.Parse, or change the culture of the current thread.

    I used French because comma is a decimal separator in this language, but of course any other language for which it's the case should fit.