简而言之,它是null,因为它应该用于数字和日期类型。
有关msdn的OpenXML文档:
对于数字和日期类型,DataType属性的值为null。 对于字符串,它包含CellValues.SharedString的值,对于布尔值,则为CellValues.Boolean。
但是,可以通过 CellFormat 上的 NumberFormatId 区分日期和数字单元格格式。 诀窍在于找到哪个ID映射到什么格式。 您可以通过创建新的Excel文件并将单元格设置为问题格式(即日期)来找出要使用的格式:
然后使用7zip提取Excel文件并查看xl / styles.xml文件:
在上面的图像中,您可以看到此formatId 14将翻译成短日期。 完整格式列表请参见Office Open XML格式的ECMA-376文档(数字格式表应该在第4部分中被埋藏。他们将其移到了第1部分的18.8.30节中)。
我创建了一个枚举来表示最常见的formatIds:
private enum Formats
{
General = 0,
Number = 1,
Decimal = 2,
Currency = 164,
Accounting = 44,
DateShort = 14,
DateLong = 165,
Time = 166,
Percentage = 10,
Fraction = 12,
Scientific = 11,
Text = 49
}
您可以创建一个辅助函数,以您所需的方式获取格式化的值:
private static string GetFormattedCellValue(WorkbookPart workbookPart, Cell cell)
{
if (cell == null)
{
return null;
}
string value = "";
if (cell.DataType == null)
{
int styleIndex = (int)cell.StyleIndex.Value;
CellFormat cellFormat = (CellFormat)workbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ElementAt(styleIndex);
uint formatId = cellFormat.NumberFormatId.Value;
if (formatId == (uint)Formats.DateShort || formatId == (uint)Formats.DateLong)
{
double oaDate;
if (double.TryParse(cell.InnerText, out oaDate))
{
value = DateTime.FromOADate(oaDate).ToShortDateString();
}
}
else
{
value = cell.InnerText;
}
}
else
{
switch (cell.DataType.Value)
{
case CellValues.SharedString:
SharedStringItem ssi = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(int.Parse(cell.CellValue.InnerText));
value = ssi.Text.Text;
break;
case CellValues.Boolean:
value = cell.CellValue.InnerText == "0" ? "false" : "true";
break;
default:
value = cell.CellValue.InnerText;
break;
}
}
return value;
}