目录

使用-Net-处理-Excel-文件的时间列

目录

使用 Net 处理 Excel 文件的时间列

前言

最近,处理Excel的情况比较多,然后,就碰到了时间列,读取出来时中文,保存到数据库中着实麻烦,就找了下如何解决这个问题。

正文

1.这是读取Excel时候,调试的时候,时间列的格式,如下图:

https://i-blog.csdnimg.cn/img_convert/bce0509dbc6aa6d085c068edd200c039.png

2.分享下原始读取Excel的公共方法,其实,也只能说这个方法写的有问题,所有列都按照字符串处理的,如下图:

 1 public static DataTable LoadExcelFile(IWorkbook workbook, string sheetName, bool isFirstRowColumn)
 2 {
 3     ISheet sheet = null;
 4     DataTable data = new DataTable();
 5     int startRow = 0;
 6     int cellCount = 0;
 7     int rowCount = 0;
 8 
 9     try
10     {
11 
12         if (sheetName != null)
13         {
14             sheet = workbook.GetSheet(sheetName);
15         }
16         else
17         {
18             sheet = workbook.GetSheetAt(0);
19         }
20 
21         if (sheet != null)
22         {
23             IRow firstRow = sheet.GetRow(0);
24             cellCount = firstRow.LastCellNum;
25             if (isFirstRowColumn)
26             {
27                 for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
28                 {
29                     DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);
30                     data.Columns.Add(column);
31                 }
32                 startRow = sheet.FirstRowNum + 1;
33             }
34             else
35             {
36                 startRow = sheet.FirstRowNum;
37             }
38 
39             rowCount = sheet.LastRowNum;
40 
41             for (int i = startRow; i <= rowCount; ++i)
42             {
43                 IRow row = sheet.GetRow(i);
44                 if (row == null)
45                 {
46                     continue;
47                 }
48 
49                 DataRow dataRow = data.NewRow();
50                 for (int j = row.FirstCellNum; j < cellCount; ++j)
51                 {
52                     ICell cell = row.GetCell(j);
53                     if (cell != null)
54                     {
55                         dataRow[j] = cell.ToString();
56                     }
57                 }
58                 data.Rows.Add(dataRow);
59             }
60         }
61         return data;
62     }
63     catch (Exception ex)
64     {
65         Console.WriteLine("Exception: " + ex.Message);
66         return null;
67     }
68 }

3.我们看一下上面代码里黄色背景的部分,就是写入DataTable的部分,其实简单的判断一下,如果是数字类型又能格式化成时间的情况,就按照时间格式读取就行了,如下图:

for (int j = row.FirstCellNum; j < cellCount; ++j)
{
    ICell cell = row.GetCell(j);
    if (cell != null)
    {
        if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
            dataRow[j] = cell.DateCellValue.ToString();
        else
            dataRow[j] = cell.ToString();
    }
}

4.我们再调试一下代码,时间格式就是正经的时间格式了,如果还不符合要求,就可以用net的转换时间函数再加工一下就行了,如下图:

https://i-blog.csdnimg.cn/img_convert/cd7b54af3b16d3d2bdb64bd045245849.png

结束语

其实,我们读取Excel的时候,不仅仅时间格式,其他格式也需要特别的处理,大家可以参考这个例子,举一反三一下。