使用VSTO获取excel列的默认数据types

有没有办法使用VSTO c#获取由excel分配给它的列的默认数据types。

您不能testing整个列的数据types,因为Excel不会将列中所有单元格的数据types限制为相同。 您将不得不testing单个单元格中保存的数据types。

只要单元格不为空,您可以通过调用单元格所持有的值的Object.GetType()方法来testing单元格所持有的数据types:

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

使用C#3.0会更麻烦一些:

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

但是,如果单元格可能为空,则必须进行testing,因为空单元格返回的Range.Valuenull ,并且无法在null上调用Object.GetType() 。 因此,你必须显式testingnull

 // 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 + "'"); 

如果使用C#3.0,代码是类似的:

 // 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 + "'"); 

希望这可以帮助…

迈克

创build一个ADO.NET DataTable,SqlConnection和SqlDataAdapter。
使用Excel工作表中的数据填充DataTable。
然后使用DataTable-> Columns [列号] – > DataType属性从数据表中获取底层数据types。

下面的代码可以帮助你更好地理解。 但是它可能不完整。

 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(); 

Excel中的列和行没有数据types。 单元格具有取决于其内容的数据types(Double,Error,String,Boolean,Empty)在单元格中有任何内容input之前它是空的。

要获取整列的数据types,可以使用下面的代码

 // Using C# 4.0 for (int i = 0; i <= cells.LastColIndex; i++) //looping all columns of row { Type type = worksheet.Cells[0,i].Format.FormatType; } 

上面的代码读取第一行中所有列的数据types。

但请记住, Excel不会限制列中所有单元格的数据types相同