.net讀取Excel轉datatable、.net讀取的Excel存在合併單元格而且轉成datatable

項目中常常會遇到Excel導入數據,Excel的模板會多是存在合併單元格的,模板以下圖所示lua

 

讀取時須要填充合併單元格的值,轉成datatable單元格值時,填充合併單元格的值,以下圖所示:spa

合併單元格的值填充,這種格式的datatable使用SqlBulkCopy批量導入更爲方便excel

Excel轉datatable方法代碼:code

        /// <summary>
        /// Excel轉DataTable
        /// </summary>
        /// <param name="filePath">excel文件路徑</param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string filePath)
        {
            DataTable dt = new DataTable();
            using (FileStream fsRead = System.IO.File.OpenRead(filePath))
            {
                IWorkbook wk = null;
                //獲取後綴名
                string extension = filePath.Substring(filePath.LastIndexOf(".")).ToString().ToLower();
                //判斷是不是excel文件
                if (extension == ".xlsx" || extension == ".xls")
                {
                    //判斷excel的版本
                    if (extension == ".xlsx")
                    {
                        wk = new XSSFWorkbook(fsRead);
                    }
                    else
                    {
                        wk = new HSSFWorkbook(fsRead);
                    }

                    //獲取第一個sheet
                    ISheet sheet = wk.GetSheetAt(0);
                    //獲取第一行
                    IRow headrow = sheet.GetRow(0);
                    //建立列
                    for (int i = headrow.FirstCellNum; i < headrow.Cells.Count; i++)
                    {
                        ICell cell = headrow.GetCell(i);
                        dt.Columns.Add(cell.ToString());
                    }
                    //讀取每行,從第二行起
                    for (int r = 1; r <= sheet.LastRowNum; r++)
                    {
                        bool result = false;
                        DataRow dr = dt.NewRow();
                        //獲取當前行
                        IRow row = sheet.GetRow(r);

                        //讀取每列
                        for (int j = 0; j < row.Cells.Count; j++)
                        {
                            ICell cell = row.GetCell(j); //一個單元格

                            if (cell.IsMergedCell && r>1)  //檢測列的單元格是否合併
                            {
                                dr[j] = dt.Rows[r-2][j];
                            }
                            else
                            {
                                dr[j] = GetCellValue(cell); //獲取單元格的值

                                if (string.IsNullOrWhiteSpace(dr[j].ToString()) && j>0)
                                {
                                    dr[j] = dr[j - 1];
                                }
                            }
                            
                                                        
                            if (dr[j].ToString() != "")//全爲空則不取
                            {
                                result = true;
                            }
                        }
                        if (result == true)
                        {
                            dt.Rows.Add(dr); //把每行追加到DataTable
                        }
                    }
                }

            }
            return dt;
        }

        #region 對單元格進行判斷取值
        /// <summary>
        /// 對單元格進行判斷取值
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank: //空數據類型 這裏類型注意一下,不一樣版本NPOI大小寫可能不同,有的版本是Blank(首字母大寫)
                    return string.Empty;
                case CellType.Boolean: //bool類型
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric: //數字類型
                    if (HSSFDateUtil.IsCellDateFormatted(cell))//日期類型
                    {
                        return cell.DateCellValue.ToString();
                    }
                    else //其它數字
                    {
                        return cell.NumericCellValue.ToString();
                    }
                case CellType.Unknown: //沒法識別類型
                default: //默認類型
                    return cell.ToString();//
                case CellType.String: //string 類型
                    {
                        if (cell.IsMergedCell)
                        {
                           
                        }
                        return cell.StringCellValue;
                    }

                case CellType.Formula: //帶公式類型
                    try
                    {
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }
        #endregion

demo下載連接: https://pan.baidu.com/s/19xjsljfWe_ezffmjKDSwVg 提取碼: udghorm

相關文章
相關標籤/搜索