且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中获取Excel单元格的数据类型

更新时间:2022-04-07 22:25:09

Excel键入数据的方法比C#宽松得多.例如,数值始终为双精度.如果使用范围对象的Value属性(互操作中的get_Value(),如果我没记错的话),如果单元格的内容和格式与那些一致,则Excel可能会返回(装箱的)decimalDateTime数据类型.

Excel has a much looser approach to typing data than C#. For example, numeric values are always doubles. If you use the Value property of the range object (get_Value() in interop, if I recall correctly), Excel will possibly return a (boxed) decimal or DateTime if the cell's contents and formatting are consistent with those data types.

如果使用Value2属性,则货币和日期值将以方框双打形式返回. (所有数字都在内部以双精度形式存储,因此,由于Excel不需要测试是否进行转换,因此Value2会稍快一些.)

If you use the Value2 property, money and date values will be returned as boxed doubles. (The numbers are all stored internally as doubles, so, because Excel doesn't need to test for whether to convert them, Value2 is slightly faster.)

因此,您可以检查列中每个值的类型,并相应地选择数据列的类型.如果要测试列是否可以具有更特定的数字类型(浮点型,整数型,短型,字节型等),则还需要检查该列中值的范围,并测试它们是否为整数

So, you could check the type of each value in a column, and choose your data column's type accordingly. If you want to test whether a column could have a more specific numeric type (float, int, short, byte, etc.), then you'll also need to check the range of values in that column, and test whether they are integers.