SqlBulkCopy - The given value of type String from the data source cannot be converted to type

SqlBulkCopy - The given value of type String from the data source cannot be converted to type of the specified target column

針對使用C#SqlBulkCopy對象遇到的問題總結
1.批量插入excel數據遇到的類型轉換問題
2.去除非數據行

以下是對應的解決辦法及代碼
1.批量插入數據報錯兩種可能,第一填寫字段對應關係的時候可能有重複的,第二是數據的字段長度不足(這個需要註釋一些字段然後慢慢放開註釋找到出錯的字段)
2.第二個直接上代碼
注:ColumnMapping 是自己手動創建的excel列名與數據庫對應表的列名一一對應的類

/// <summary>
        /// 
        /// </summary>
        /// <param name="P_str_Excel">excel file name</param>
        /// <param name="P_str_SheetName"></param>       
        public void ImportDataToSql(string P_str_Excel, string DestinationTableName, ColumnMappingCollection collectionMapping, bool ifClearContent = false)
        {
            //DataSet myds = new DataSet();                               //創建數據集對象
            try
            {
                string P_str_SheetName = GetSheetName(P_str_Excel)[0];
                //獲得全部數據
                string P_str_OledbCon;
                if (Environment.Is64BitOperatingSystem == false)
                    P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                else
                    P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);     //創建Oledb數據庫連接對象
                string P_str_ExcelSql;                             //記錄要執行的Excel查詢語句
                OleDbDataAdapter oledbda = null;                            //創建Oledb數據橋接器對象
                P_str_ExcelSql = string.Format("select * from [{0}$]", P_str_SheetName);    //記錄要執行的Excel查詢語句
                oledbda = new OleDbDataAdapter(P_str_ExcelSql, P_str_OledbCon);     //使用數據橋接器執行Excel查詢

                DataTable importedTable = new DataTable();
                importedTable.Columns.Clear();

                oledbda.Fill(importedTable);                            //填充數據

                if (ifClearContent)
                {
                    //清楚非內容行
                    ColumnMapping firstColumn = collectionMapping.FindbyFileIndex(0);
                    List<DataRow> deleteList = new List<DataRow>();
                    foreach (DataRow item in importedTable.Rows)
                    {
                        if (item[0].ToString() != firstColumn.FileFieldName)
                            item.Delete();
                        else
                            break;
                    }

                    int i = 0;
                    foreach (var item in collectionMapping)
                    {
                        importedTable.Columns[i].Caption = item.FileFieldName;
                        importedTable.Columns[i].ColumnName = item.FileFieldName;
                        i++;
                    }

                    importedTable.AcceptChanges();
                    oledbda.Update(importedTable);
                }

                using (SqlBulkCopy bcp = new SqlBulkCopy(ConnectString))         //用bcp導入數據
                {
                    bcp.BatchSize = 100;                                //每次傳輸的行數
                    bcp.DestinationTableName = DestinationTableName;             //定義目標表
                    foreach (var item in collectionMapping)
                    {
                        bcp.ColumnMappings.Add(item.FileFieldName, item.DataColumnName);
                    }
                    
                    bcp.WriteToServer(importedTable);                      //將數據寫入Sql Server數據表
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private List<string> GetSheetName(string P_str_Excel)                           //獲取所有工作表名稱
        {
            List<string> P_list_SheetName = new List<string>();                     //創建泛型集合對象
            string P_str_OledbCon;
            if (Environment.Is64BitOperatingSystem == false)
                P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            else
                P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            OleDbConnection olecon = new OleDbConnection(P_str_OledbCon);                                         //連接Excel數據庫
            olecon.Open();                                              //打開數據庫連接
            System.Data.DataTable DTable = olecon.GetSchema("Tables");                  //創建表對象
            DataTableReader DTReader = new DataTableReader(DTable);                 //創建表讀取對象
            while (DTReader.Read())                                     //循環讀取
            {
                string P_str_Name = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim(); //記錄工作表名稱
                if (!P_list_SheetName.Contains(P_str_Name))                     //判斷泛型集合中是否已經存在該工作表名稱
                    P_list_SheetName.Add(P_str_Name);                           //將工作表名添加到泛型集合中
            }
            DTable = null;                                              //清空表對象
            DTReader = null;                                            //清空表讀取對象
            olecon.Close();                                             //關閉數據庫連接
            return P_list_SheetName;                                        //返回得到的泛型集合
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章