[英]Get the Default datatype for excel column using VSTO
有没有办法使用 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 + "'");
创建ADO.NET DataTable、SqlConnection 和 SqlDataAdapter。
用 Excel 工作表中的数据填充数据表。
然后使用DataTable->Columns[the column number]->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();
要获取整列的数据类型,您可以使用以下代码
// 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 并不限制列中所有单元格的数据类型必须相同。
Excel 中的列和行没有数据类型。 单元格的数据类型取决于它们的内容(Double、Error、String、Boolean、Empty)在单元格输入任何内容之前,它是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.