2013-10-12 59 views
0

我正在處理一個asp.net,其中我必須將所有Excel數據導入到SQL Server表中。爲此,我已經使用了一個文件上傳到上傳Excel文件並點擊鏈接,我將所有的Excel數據到SQL Server 2008上的按鈕,點擊下面的代碼我用:如何將Excel數據插入到使用asp.net 2012的SQL Server數據庫中

protected void ImportNow_Click(object sender, EventArgs e) 
{ 
    private static string _connStr = System.Configuration.ConfigurationManager.AppSettings["Database1"].ToString(); 
     try 
     { 
      if ((fileuploadExcel.FileName != "")) 
      { 
       string extension = Path.GetExtension(fileuploadExcel.PostedFile.FileName); 
       string excelConnectionString; 
       SqlConnection conn = new SqlConnection(_connStr); 
       string tableName = "School"; 
       string path = fileuploadExcel.PostedFile.FileName; 

       //Create connection string to Excel work book 
       if (extension == ".xls") 
       { 
        excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + 
                  ";Extended Properties=Excel 8.0;Persist Security Info=False"; 
       } 
       else 
       { 
        excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + 
                 ";Extended Properties=Excel 12.0;Persist Security Info=False"; 
       } 

       //Create Connection to Excel work book 
       OleDbConnection excelConnection = new OleDbConnection(excelConnectionString); 
       //Create OleDbCommand to fetch data from Excel    
       conn.Open(); 
       SqlCommand comm = new SqlCommand("truncate table " + tableName, conn); 
       SqlCommand identityChange = conn.CreateCommand(); 
       identityChange.CommandText = "SET IDENTITY_INSERT " + tableName + " ON"; 
       OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection); 
       excelConnection.Open(); 
       OleDbDataReader dReader; 
       dReader = cmd.ExecuteReader(); 
       identityChange.ExecuteNonQuery(); 
       SqlBulkCopy sqlBulk = new SqlBulkCopy(_connStr); 
       //Give your Destination table name 
       sqlBulk.DestinationTableName = tableName; 
       sqlBulk.WriteToServer(dReader); 
       excelConnection.Close(); 
       conn.Close(); 
       lblMessage.ForeColor = Color.Green; 
       lblMessage.Text = "Import into table <b>" + tableName + "</b> successful!<br />"; 
      } 
      else 
      { 
       lblMessage.ForeColor = Color.Red; 
       lblMessage.Text = "Please first upload (Select) excel file."; 
      } 
     } 
     catch (Exception ex) 
     { 
      throw (ex); 
     } 
    } 

當我上傳的Excel文件並讀取它然後顯示錯誤

Microsoft Office Access數據庫引擎找不到對象'Sheet1 $'。確保對象存在,並且正確拼寫其名稱和路徑名。

即使有一個文件有Sheet1。請幫幫我。 Thanx

+0

這可能涉及到該文件是在相關代碼。這是上傳的文件嗎?還要確保ASP進程有足夠的權限來查看該文件。 – Rikalous

+0

是的,這是一個上傳的文件。 –

+0

那很可能是一個權限問題。 – Rikalous

回答

0

驗證上傳文件的路徑在賦予數據源時是否有效。由於代碼

string path = fileuploadExcel.PostedFile.FileName; 

會在某些瀏覽器無法在獲取文件路徑,see herehere。 嘗試指定地方是會得到保存爲文件的路徑,

string path = @"c:\documents\files\"+ fileuploadExcel.PostedFile.FileName; 
相關問題