2017-04-09 68 views
0

我有一個Excel文件,我需要將其插入到sqlserver的,所以我得到這個代碼中插入這是插入方法:無法從Excel檢索指定數據文件

private void InsertDaily_Inventory(string FilePath) 
    { 
     try { 
      using (SqlConnection conn = new SqlConnection("Data Source=(local);Database='SimDevice_Stocks';Integrated Security=yes;")) 
      { 
       conn.Open(); 

       SqlCommand cmd = new SqlCommand("Delete Temp_DailyInventory", conn); 
       cmd.ExecuteNonQuery(); 

       //SqlCommand cmd1 = new SqlCommand("alter table Temp_DailyInventory alter column Order_Date nvarchar(200)", conn); 
       //cmd1.ExecuteNonQuery(); 
       conn.Close(); 

      } 

      constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;""", FilePath); 
      Econ = new OleDbConnection(constr); 
      SqlConnection con = new SqlConnection("Data Source=(local);Database='SimDevice_Stocks';Integrated Security= yes;"); 

      Query = string.Format("Select [ORDER_SUB_TYPE],[ORDER_DATE],[ORDER_STATUS],[SIM_NETWORK_TYPE],[STORE_ID],[ROOT_PRODUCT_ATM_TYPE],[STC_ERP_SIM_ITEM],[STC_SALECO_ITEM_CODE] FROM [{0}] where (ORDER_SUB_TYPE='Change SIM' OR ORDER_SUB_TYPE='New') and ORDER_STATUS='Complete' and (ROOT_PRODUCT_ATM_TYPE = 'Prepaid' OR ROOT_PRODUCT_ATM_TYPE = 'Postpaid') and STORE_ID Like 'S' ", "Online_Inventory_Open_Points_re$"); 
      OleDbCommand Ecom = new OleDbCommand(Query, Econ); 
      Econ.Open(); 

      DataSet ds = new DataSet(); 
      OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ); 
      Econ.Close(); 
      oda.Fill(ds); 
      DataTable Exceldt = ds.Tables[0]; 
      //connection(); 
      //creating object of SqlBulkCopy  
      SqlBulkCopy objbulk = new SqlBulkCopy(con); 
      //assigning Destination table name  
      objbulk.DestinationTableName = "Temp_DailyInventory"; 
      //Mapping Table column  
      objbulk.ColumnMappings.Add("ORDER_SUB_TYPE", "Order_Sub_Type"); 
      objbulk.ColumnMappings.Add("Order_Date", "Order_Date"); 
      objbulk.ColumnMappings.Add("ORDER_STATUS", "Order_Status"); 
      objbulk.ColumnMappings.Add("SIM_NETWORK_TYPE", "Sim_Network_Type"); 
      objbulk.ColumnMappings.Add("STORE_ID", "Store_ID"); 
      objbulk.ColumnMappings.Add("ROOT_PRODUCT_ATM_TYPE", "Root_Product_Atm_Type"); 
      objbulk.ColumnMappings.Add("STC_ERP_SIM_ITEM", "Stc_Erp_Sim_Item"); 
      objbulk.ColumnMappings.Add("STC_SALECO_ITEM_CODE", "Stc_Saleco_Item_Code"); 


      //inserting Datatable Records to DataBase  
      con.Open(); 
      objbulk.WriteToServer(Exceldt); 


      using (SqlCommand cmd3 = new SqlCommand("UPDATE Temp_DailyInventory SET Order_Date = LEFT(Order_Date, CHARINDEX(' ', Order_Date) - 1) WHERE CHARINDEX(' ', Order_Date) > 0", con)) 
      { 
       cmd3.ExecuteNonQuery(); 

      } 



      con.Close(); 
     } 
     catch(Exception ex) 
     { 

     } 
     } 

,然後按鈕,點擊它插入

protected void InsertInventoryFile_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      // string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName); 
      //InsertDaily_Inventory(CurrentFilePath); 

      if (FileUpload1.PostedFile != null) 
       if (FileUpload1.FileName.EndsWith(".xlsx")) 
       { 
        try 
        { 
         if (!Directory.Exists(Server.MapPath("~/ExcelFiles/InventoryFiles/"))) 
          Directory.CreateDirectory(Server.MapPath("~/ExcelFiles/InventoryFiles/")); 

         string fileName = Guid.NewGuid().ToString(); 
         string fullPath = Server.MapPath("~/ExcelFiles/InventoryFiles/") + fileName + ".xlsx"; 
         FileUpload1.SaveAs(fullPath); 

         //DataTable table = Excel.Import.Query(fullPath); 
         InsertDaily_Inventory(fullPath); 
         Response.Write(@"<script langauge='javascript'>alert('Data Imported')</script>"); 


        } 
        catch (Exception ex) 
        { 
         Response.Write(@"<script langauge='javascript'>alert('"+ex.Message+"')</script>"); 
        } 
       } 
     } 

     catch(Exception exx) 
     { 

     } 
    } 

所以數據包含像「SCCC387」一些數據的不插入他們喜歡「1023」號的只插入存儲ID的記錄,如果有任何代碼,以幫助我插入來自數據excel到sqlserver數據庫請不要猶豫,把它給我 在此先感謝

回答

0

您正在使用批量複製,也許您應該獨立處理每行以處理可能的錯誤。同時驗證你的列的類型。 Excel驅動程序默認根據前8行確定類型。

我強烈建議您儘可能使用SSIS進行數據加載和集成。如果你有SQL服務器標準版,你有SSIS。

0

有了您可以使用創建的OleDbConnection連接如到Excel文件中的filelocation:

String[] excelSheets = new String[dt.Rows.Count]; 
int t = 0; 
//get the list of excelSheetNames 
foreach (DataRow row in dt.Rows) 
{ 
    excelSheets[t] = row["TABLE_NAME"].ToString(); 
    t++; 
}      
string query = string.Format("Select * from [{0}]", excelSheets[0]); 
System.Data.DataSet ds = new System.Data.DataSet(); 
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection)) 
{ 
    dataAdapter.Fill(ds); 
} 
if (ds.Tables.Count > 0) 
{ 
    DataTable tb = ds.Tables[0]; 
    return tb; 
} 

在了AppConfig:

string excelConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString + fileLocation; 
//connection String for xls file format. 
if (fileExtension == ".xls") 
{ 
    excelConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString + fileLocation; 
} 
//connection String for xlsx file format. 
else if (fileExtension == ".xlsx") 
{ 
    excelConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString + fileLocation;       
} 
//Create Connection to Excel work book 
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
excelConnection.Open(); 

然後你就可以用這個跟隨着代碼檢查Excel中的數據您需要讓connectionString提供商優化:

<add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" /> 
<add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" /> 

讓我知道這是否有助於你。

+0

感謝您的幫助,但沒有做任何事情 – ahmad