C# 从Excel表格读取数据存入 DataTable 对象 在从DataTable存入数据库 SQL SERVER

ExcelUtil工具类

 #region Excel导入Datable
        /// 
        /// Excel导入Datable
        /// 
        /// 导入路径(包含文件名与扩展名)
        /// 
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else if (fileExt == ".xls")
                {
                    workbook = new HSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }

                if (workbook == null)
                {
                    return null;
                }
                //获取工作簿Sheet 第一个 根据索引
                ISheet sheet = workbook.GetSheetAt(0);

                //获取表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);

                List columns = new List();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                    {
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    }
                    columns.Add(i);
                }

                //数据
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// 
        /// 获取单元格类型
        /// 
        /// 
        /// 
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion

从DataTable 存入SQL SERVER

 /// 
        /// 从DataTable 插入数据到数据库
        /// 
        /// DataTable数据源
        /// 插入的表名
        /// DataTable表头的名称与数据库列表对应的字典集合
        /// 
        public static int SqlbulkcopyInsert(DataTable dt, string tableName, Dictionary dic)
        {
            try
            {
              //  string defaultConnectionString = ConfigurationManager.ConnectionStrings["mainDB"].ConnectionString;
             // defaultConnectionString 连接字符串
                using (SqlBulkCopy bcp = new SqlBulkCopy(defaultConnectionString))
                {
                  
                    //设置要批量写入的表  
                    bcp.DestinationTableName = tableName;
                    foreach (KeyValuePair kv in dic)
                    {
                        bcp.ColumnMappings.Add(kv.Key, kv.Value);
                    }
                    bcp.WriteToServer(dt);
                }
                return 1;
            }
            catch (Exception e)
            {
                return 0;
            }
            finally
            {

            }
        }

 

你可能感兴趣的:(.NET,C#)