Search code examples
c#exceloledbtype-conversion

Getting integer values out of an standard formatted excel field using OLE DB


I use OLE DB to convert excel files into tab-stop separated text files. In this excel files could be i.e. GTIN or EAN codes. If a excel column is formatted as standard it will cut for example 54260279477798 to 5,42602E+13 and this is the same string I get to my file.

My OLE DB connection string looks like this:

Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={filename};
Extended Properties="Excel 12.0 Xml;HDR=NO;IMEX=1";

And my code where I get it to a string looks like this:

for (int x = 0; x < tDataTable.Rows.Count; x++)
{
    string tRowString = String.Empty;

    for (int y = 0; y < tDataTable.Columns.Count; y++)
    {
        if (y == maxColumns)
        {
            tRowString += tDataTable.Rows[x][y].ToString();
        }
        else
        {
            tRowString += tDataTable.Rows[x][y].ToString() + "\t";
        }
    }
    tRowString = Regex.Replace(tRowString, @"(?<!\r)\n", "");
    tStreamWriter.WriteLine(tRowString);
}

I access the sheet using

tCommand = new OleDbCommand("SELECT * FROM [" + "Tabelle1" + "$]", tConnection)
{
    CommandType = CommandType.Text
};

Is there anyway to reformat the values while extracting them?


Solution

  • A friend if mine showed me an solution. I had to parse it to double.

    string tColumnString = String.Empty;
    
    tColumnString = tDataTable.Rows[x][y].ToString();
    
    if (tColumnString.Contains("e+013") || tColumnString.Contains("e+012") || tColumnString.Contains("e+011") || tColumnString.Contains("e+07"))
    {
        double tColumnDouble = 0;
        if (double.TryParse(tColumnString, out tColumnDouble))
        {
            Console.WriteLine("Double konvertiert: " + tColumnDouble.ToString());
            tColumnString = Convert.ToString(tColumnDouble);
        }
    }
    

    I hope this could help someone else, too.