有没有一种方法可以使用VSTO c#获取Excel分配给其列的默认数据类型。
由于Excel不限制列中所有单元格的数据类型必须相同,因此您无法测试整个列的数据类型。您需要测试单个单元格中保存的数据类型。
只要单元格不为空,就可以通过调用Object.GetType()
方法来测试单元格保存的数据类型:
// Using C# 4.0
Type type = worksheet.Cells[1,1].Value.GetType();
// Using C# 3.0
Type type = (worksheet.Cells[1, 1] as Excel.Range).get_Value(Type.Missing).GetType();
如果单元格可以为空,那么你需要进行测试,因为空单元格返回的Range.Value
是null
,你无法在null
上调用Object.GetType()
。因此,你需要明确测试null
:
// 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 + "'");
// 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 + "'");
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();
// 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;
}