c# - 使用 VSTO 获取 excel 列的默认数据类型

标签 c# excel vsto types

有没有办法使用 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.Valuenull,您可以不要在 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/

相关文章:

excel - Text.Contains 如果文本包含关键字作为子文本

excel - excel中按ID返回的最大值

c# - 为什么 VSTO Word ContentControl 没有 Name 属性?

c# - 如何从以特定名称开头的 appsettings 键中获取所有值并将其传递给任何数组?

c# - SVM 可以增量学习吗?

c# - DrawItemEventArgs 的 "Index"属性有时会变为负数

excel - VBA 如何如果不是并转到下一页

c# - 寻找一种更灵活的方法将定界字符串转换为 StringDictionary

unit-testing - 如何对 Excel VBA 代码进行单元测试

c# - 从 Excel 数据验证中删除帮助按钮