我正忙于开发一个从 MS Excel (2016) 文件导入数据的组件。 该组件使用 MS OpenXML SDK2.5 库。 MS Excel 的最终用户安装基于荷兰国家/地区设置。 该文件包含一列财务数据(数字)等。该列的位置事先未知。
为了确定单元格是否包含数字数据,我评估属性 Cell.DataType(类型为 CellValues,是一个枚举)。 乍一看,这个属性似乎是确定这一点的完美候选者。 CellValues 的可能值为: bool 值、数字、错误、共享字符串、字符串、内联字符串或日期。所以我希望 Cell.DataType 设置为 CellValues.Number。 经过一些调试后,我发现当单元格包含数字数据时,Cell.DataType 为 null。
在互联网上搜索解释时,我发现了以下 MSDN 文章: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx
这篇文章准确地描述了我在调试过程中发现的内容:
The Cell type provides a DataType property that indicates the type of the data within the cell. The value of the DataType property is null for numeric and date types.
有人知道为什么 Cell.DataType 没有分别用 CellValues.Number 或 CellValues.Date 初始化吗?
确定单元格是否包含数值的最佳方法是什么?
最佳答案
Does anybody know why Cell.DataType is not initialized with respectively CellValues.Number or CellValues.Date?
从here看ECMA-376标准,Cell
的(缩写)XSD 如下所示:
<xsd:complexType name="CT_Cell">
...
<xsd:attribute name="t" type="ST_CellType" use="optional" default="n"/>
...
</xsd:complexType>
该属性代表类型。请注意,它是可选的,默认值为“n”
。第 18.18.11 节 ST_CellType(单元类型)列出了该类型的有效值:
b - boolean
d - date
e - error
inlineStr - an inline string
n - number (the default)
s - a shared string str - a formula string
您可以看到“n”
代表一个数字
。
What is the best way to determine if a cell contains a numeric value?
从上面看来,您可以检查 Cell.DataType
或 Cell.DataType
为 CellValues.Number
来判断一个单元格是否包含数字,但事情并不那么简单 - 大问题是日期。
日期的原始存储机制似乎是使用数字并依靠样式来知道该数字是否实际上是数字或者该数字是否代表日期。
令人困惑的是,规范已更新为包含 Date
类型,但并非所有日期都会使用日期类型。 Date
类型意味着单元格包含 ISO 8601 格式的日期,但它对于将日期存储为具有正确样式的数字来说是完全有效的。例如,以下 XML 代码段以 Number
和 Date
格式显示相同的日期(2017 年 2 月 1 日):
<sheetData>
<row r="1" spans="1:1" x14ac:dyDescent="0.25">
<c r="A1" s="1">
<v>42767</v>
</c>
</row>
<row r="2" spans="1:1" x14ac:dyDescent="0.25">
<c r="A2" s="1" t="d">
<v>2017-02-01</v>
</c>
</row>
</sheetData>
在 Excel 中打开时如下所示:
如果您需要区分日期和数字,那么您将需要查找任何数字(空 Cell.DataType
或 CellValues 的
),然后检查这些单元格的样式以确保它们是数字而不是伪装成数字的日期。Cell.DataType
)。 Number
关于c# - OpenXML SDK2.5(Excel): How to determine if a cell contains a numeric value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42390713/