c# - OpenXML SDK2.5(Excel): How to determine if a cell contains a numeric value?

标签 c# excel openxml-sdk

我正忙于开发一个从 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.DataTypeCell.DataTypeCellValues.Number 来判断一个单元格是否包含数字,但事情并不那么简单 - 大问题是日期。

日期的原始存储机制似乎是使用数字并依靠样式来知道该数字是否实际上是数字或者该数字是否代表日期。

令人困惑的是,规范已更新为包含 Date 类型,但并非所有日期都会使用日期类型Date 类型意味着单元格包含 ISO 8601 格式的日期,但它对于将日期存储为具有正确样式的数字来说是完全有效的。例如,以下 XML 代码段以 NumberDate 格式显示相同的日期(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 中打开时如下所示:

The resulting Excel file

如果您需要区分日期和数字,那么您将需要查找任何数字(空 Cell.DataTypeCellValues 的 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/

相关文章:

C# OpenXML 判断段落是否为隐藏文本

c# - 将流转换为字节串

c# - 使用 Elasticsearch 将数组字段映射到 C# 字符串列表

cricinfo记分卡的html解析

c# - 使用 OpenXML 创建合并单元格

c# - OpenXml-SDK:如何将 FontFamily/Size 应用于 [TextPlain] 类型的 AltChunk

c# - 无法在多个 Chrome 实例上运行 Selenium Grid 3.0.1

c# - 编辑记录时 RadGrid 中的 "Cannot unregister UpdatePanel with ID ' xxx ' since it was not registered with the ScriptManager... "

excel - SUMIF 公式中的嵌套 MIN

vba - 如何在多张纸上应用卡住 Pane ?