在C#中获取Excel单元格的数据类型 [英] Get Data Type of an Excel Cell in C#

查看:756
本文介绍了在C#中获取Excel单元格的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从XLSX工作表中读取值,并将它们放入数据表中.

I am reading in values from an XLSX Worksheet and putting them into a Data table.

我的问题是我似乎无法推断出单元格的数据类型,因此无法设置数据表的列类型.

My problem is that I cannot seem to infer the Datatype of the cell so that I can set the Data table's Column type.

推荐答案

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.

这篇关于在C#中获取Excel单元格的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆