1. 程式人生 > >EPPlus匯入DataTable日期時間的處理

EPPlus匯入DataTable日期時間的處理

當我們用EPPlus匯入Excel資料到DataTable中,如果某列是DateTime格式 ,我們應該如何處理呢?

解決思路:

1、首先要獲取excel中的列的格式型別

2、判斷格式型別是否是日期時間

關鍵程式碼如下:

public static DataTable ExcelToDt(string filePath, bool isSkipFirstRow, int cols, string logBusiness)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                try
                {
                    DataTable dt = new DataTable();
                    for (int col = 0; col < cols; col++)
                    {
                        dt.Columns.Add(col.ToString(), Type.GetType("System.String"));
                    }
                    Stream stream = new FileStream(filePath, FileMode.Open);
                    using (stream)
                    {
                        ExcelPackage package = new ExcelPackage(stream);
                        ExcelWorksheet sheet = package.Workbook.Worksheets[1];
                        int startRowIndx = sheet.Dimension.Start.Row + (isSkipFirstRow ? 1 : 0);
                        for (int r = startRowIndx; r <= sheet.Dimension.End.Row; r++)
                        {
                            DataRow dr = dt.NewRow();
                            for (int c = sheet.Dimension.Start.Column; c <= sheet.Dimension.End.Column; c++)
                            {
                                if (sheet.Cells[r, c].Style.Numberformat.Format.IndexOf("yyyy") > -1
                                    && sheet.Cells[r,c].Value!=null)//注意這裡,是處理日期時間格式的關鍵程式碼
                                {

                                    dr[c - 1] = sheet.Cells[r, c].GetValue<DateTime>();
                                }
                                else
                                    dr[c - 1] = (sheet.Cells[r, c].Value ?? DBNull.Value);
                            }
                            dt.Rows.Add(dr);
                        }
                    }
                    return dt;
                }
                catch (Exception ex)
                {
                    log.WriteLog(string.Concat(new string[]
                    {
                        LogConst.SEPARATION,
                        logBusiness,MSG,
                        LogConst.SEPARATION,
                        Environment.NewLine,
                        ex.Message,
                        Environment.NewLine
                    }));
                    return null;
                }
            }
            return null;
        }