NPOI导入Excel日期格式的处理

传统操作Excel方法在部署的时候遇到很多问题,如目标主机需要安装Excel、64位电脑不支持、需要安装相关驱动程序等。所以我们一般会使用开源的NPOI来替代传统的Excel操作方法,NPOI的优点是只需引入相关的库就可以在没有安装Office的情况下对Word或Excel文档进行读写操作。

问题描述

在处理Excel的过程中可能会遇到各种各样的数据格式的问题,比如日期格式问题,日期的格式可以说是有各式各样的,如果我们不能正确处理可能会导致我们导入之后得不到自己想要的值。

解决方案

可以从NPOI的cell中获取CellStyle的DataFormat,通过判断cell的数据类型决定要不要当做日期处理。

if (cell.CellType == CellType.NUMERIC)
{
    short format = cell.CellStyle.DataFormat;
    if (format == 0xe || format == 0x16)
    {
        DateTime date = cell.DateCellValue;
        dataRow[j] = date.ToString();
    }
    else
    {
        dataRow[j] = cell.NumericCellValue;
    }
}

类型匹配表

下面是从官网扒来的cell类型匹配表:

0, "General"
1, "0"
2, "0.00"
3, "#,##0"
4, "#,##0.00"
5, "$#,##0_);($#,##0)"
6, "$#,##0_);[Red]($#,##0)"
7, "$#,##0.00);($#,##0.00)"
8, "$#,##0.00_);[Red]($#,##0.00)"
9, "0%"
0xa, "0.00%"
0xb, "0.00E+00"
0xc, "# ?/?"
0xd, "# ??/??"
0xe, "m/d/yy"
0xf, "d-mmm-yy"
0x10, "d-mmm"
0x11, "mmm-yy"
0x12, "h:mm AM/PM"
0x13, "h:mm:ss AM/PM"
0x14, "h:mm"
0x15, "h:mm:ss"
0x16, "m/d/yy h:mm"

// 0x17 - 0x24 reserved for international and undocumented 0x25, "#,##0_);(#,##0)"
0x26, "#,##0_);[Red](#,##0)"
0x27, "#,##0.00_);(#,##0.00)"
0x28, "#,##0.00_);[Red](#,##0.00)"
0x29, "_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)"
0x2a, "_($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)"
0x2b, "_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)"
0x2c, "_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)"
0x2d, "mm:ss"
0x2e, "[h]:mm:ss"
0x2f, "mm:ss.0"
0x30, "##0.0E+0"
0x31, "@" - This is text format.
0x31 "text" - Alias for "@"

传送门

转载请注明出处:http://www.cnblogs.com/keitsi/p/8572093.html

原文地址:https://www.cnblogs.com/keitsi/p/8572093.html