views:

258

answers:

3

Is there a way to get the default datatype assigned by excel to its columns using VSTO c#.

A: 

Columns and Rows in Excel don't have Datatypes. Cells have Datatypes which depend on their content (Double,Error,String,Boolean, Empty) Before a cell has anything entered into it it is Empty.

Charles Williams
Is there a way to know that datatype of the cell using VSTO C#
Kavita A
A: 

You can't test the data type of the entire column because Excel does not restrict the data types of all the cells in the column to be the same. You would have to test the data type held in individual cells.

As long as the cell is not empty, you can test for the data type held by the cell by calling the Object.GetType() method on the value held by the cell:

// Using C# 4.0
Type type = worksheet.Cells[1,1].Value.GetType();

Using C# 3.0 would be a little more cumbersome:

// Using C# 3.0
Type type = (worksheet.Cells[1, 1] as Excel.Range).get_Value(Type.Missing).GetType();

If the cell could be empty, however, you'll have to test for that because the 'Range.Value' returned by an empty cell is null, and you can't call Object.GetType() on null. Therefore, you have to test for null explicitly:

// Testing Cell Data Type via C# 4.0

object value = worksheet.Cells[1,1].Value;

string typeName;

if (value == null)
{
    typeName = "null";
}
Else
{
    typeName = value.GetType().ToString();
}

MessageBox.Show("The value held by the cell is a '" + typeName + "'");

If using C# 3.0, the code is similar:

// Testing Cell Data Type via C# 3.0

object value = (worksheet.Cells[1, 1] as Excel.Range).get_Value(Type.Missing);

string typeName;

if (value == null)
{
    typeName = "null";
}
Else
{
    typeName = value.GetType().ToString();
}

MessageBox.Show("The value held by the cell is a '" + typeName + "'");

Hope this helps...

-- Mike

Mike Rosenblum
A: 

Create a ADO.NET DataTable, SqlConnection and SqlDataAdapter.
Fill the DataTable with data from the Excel Sheet.
Then get the underlying data type from the datatable using the DataTable->Columns[the column number]->DataType property.

The code below may help you understand better. However it may not be complete.

/*

        DataTable dtSourceData = new DataTable(); //ADO.NET
        string Con_Str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + <Excel file path> + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";

        OleDbConnection con = new OleDbConnection(Con_Str);//ADO.NET
        con.Open();

        String qry = "SELECT * FROM [Sheet1$]"; 
        OleDbDataAdapter odp = new OleDbDataAdapter(qry, con);//ADO.NET
        odp.Fill(dtSourceData);

        con.Close();

*/

redsunbeer