有没有办法使用 VSTO c# 获取 excel 分配给其列的默认数据类型。
最佳答案
不能测试整列的数据类型,因为Excel不限制列中所有单元格的数据类型必须相同。您必须测试单个单元格中保存的数据类型。
只要单元格不为空,您就可以通过对单元格保存的值调用 Object.GetType()
方法来测试单元格保存的数据类型:
// 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();
但是,如果单元格可能为空,则您必须对此进行测试,因为空单元格返回的 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 + "'");
如果使用 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 + "'");
关于c# - 使用 VSTO 获取 excel 列的默认数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2672956/