使用VSTO获取Excel列的默认数据类型

3

有没有一种方法可以使用VSTO c#获取Excel分配给其列的默认数据类型。

4个回答

4

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

2
创建一个 ADO.NET 的 DataTable、SqlConnection 和 SqlDataAdapter。
从 Excel 表格中填充 DataTable。
然后使用 DataTable->Columns[列号]->DataType 属性获取数据表的底层数据类型。
以下代码可能有助于您更好地理解。 但它可能不完整。
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();

1
要获取整个列的数据类型,您可以使用以下代码
// 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;
  }

以上代码读取第一行中所有列的数据类型。
但请记住,Excel不限制列中所有单元格的数据类型必须相同。

0
Excel中的列和行没有数据类型。 单元格的数据类型取决于其内容(Double、Error、String、Boolean、Empty)。 在单元格输入任何内容之前,它都是空的。

有没有办法使用VSTO C#知道单元格的数据类型? - Arshya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接