2013-10-16 31 views
1

嗨。我想將excel表單數據導入到SQL服務器表中,因爲我編寫的代碼如下所示。片材被上傳到文件夾,但數據不會導入到表中,任何人都可以請告訴我哪裏是錯誤....如何將excel表單中的數據導入到sql server表中?

public partial class upload2 : System.Web.UI.Page 
    { 
     private string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       PopulateDatabaseTables(); 
      } 
     } 

     private void PopulateDatabaseTables() 
     { 
      string tableName = string.Empty; 
      string sql = "SELECT *, name AS table_name " + 
       " FROM sys.tables WHERE Type = 'U' ORDER BY table_name"; 
      using (SqlConnection conn = new SqlConnection(connStr)) 
      { 
       using (DataTable table = new DataTable()) 
       { 
        conn.Open(); 
        using (SqlDataAdapter dAd = new SqlDataAdapter(sql, conn)) 
        { 
         dAd.Fill(table); 
        } 
        ListBox1.DataSource = table; 
        ListBox1.DataBind(); 
       } 
      } 
     } 

     protected void ImportNow_Click(object sender, EventArgs e) 
     { 
      if (ListBox1.SelectedValue == "") 
      { 
       lblMessage.ForeColor = Color.Red; 
       lblMessage.Text = "Please select table in which you want to import data from excel sheet"; 
      } 
      else if ((fileuploadExcel.FileName != "")) 
      { 
       string extension = Path.GetExtension(fileuploadExcel.PostedFile.FileName); 

       string excelConnectionString; 
       SqlConnection conn = new SqlConnection(connStr); 
       string tableName = ListBox1.SelectedValue; 
       // string path = fileuploadExcel.PostedFile.FileName; 
       string path = Server.MapPath("~/fileuploadExcel/" + fileuploadExcel.FileName); 
       fileuploadExcel.SaveAs(path); 
       Response.Write("path=" + path); 
       return; 
       //Create connection string to Excel work book 
       if (extension == ".xlsx") 
       { 
        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;sData Source= + path + 
                 ;Extended Properties=Excel 12.0;Persist Security Info=False"; 
       } 

       //Create Connection to Excel work book 
       SqlConnection excelConnection = new SqlConnection(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"; 
       SqlCommand cmd = new SqlCommand("Select * from [Sheet1$]", excelConnection); 
       excelConnection.Open(); 
       SqlDataReader 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."; 
      } 
     } 

     protected void viewdata_Click(object sender, EventArgs e) 
     { 
      BindData(); 
     } 

     private void BindData() 
     { 
      try 
      { 
       if (ListBox1.SelectedValue == "") 
       { 
        lblMessage.ForeColor = Color.Red; 
        lblMessage.Text = "Please select table for which you want to view data in Gridview"; 
       } 
       else 
       { 
        string tableName = ListBox1.SelectedValue; 
        SqlConnection conn = new SqlConnection(connStr); 
        SqlDataAdapter sda = new SqlDataAdapter("select * from " + tableName, conn); 
        DataSet ds = new DataSet(); 
        sda.Fill(ds); 
        gvdetails.DataSource = ds; 
        gvdetails.DataBind(); 
       } 
      } 
      catch (DataException de) 
      { 
       lblMessage.Text = de.Message; 
       lblMessage.ForeColor = System.Drawing.Color.Red; 
      } 
     } 

     protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e) 
     { 
      gvdetails.PageIndex = e.NewPageIndex; 
      BindData(); 
     } 
    } 
} 
+0

LINQ to Excel會節省相當多的麻煩。 http://code.google.com/p/linqtoexcel/ – James

回答

0

你爲什麼不使用MS SQL Server導入和導出嚮導.. 這是最簡單的方法。

reffer這個網址,你可以得到exect的想法。 Click Here to View

希望它可以幫助你......

+0

我認爲OP想要創建一個自動化的流程/可執行文件來完成這項任務。 –

1

excelConnectionString = @ 「供應商= Microsoft.Jet.OLEDB.4.0;數據源= + path + ;擴展屬性= Excel的8.0;堅持安全信息=假」;

這裏你直接使用path,修改excelConnectionString如下

excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0} 
                 ;Extended Properties=Excel 8.0;Persist Security Info=False",path); 
0

如果你沒有在服務器上安裝Office您可能會發現它不會找到你的連接字符串中的商...

Provider=Microsoft.Jet.OLEDB.4.0; 

Provider=Microsoft.ACE.OLEDB.12.0 

不幸的,但微軟從來沒有設計它沒有服務器主機付出額外他們的服務器上運行Office工作。

相關問題