2013-10-16 1 views
1

안녕하세요. Excel 시트 데이터를 SQL 서버 테이블로 가져 오려고합니다. 아래 코드를 작성했습니다. 시트는 사람이 말해 줄 수, 폴더에 업로드되어 있지만 데이터가 테이블에 가져올 수 없습니다 바랍니다 어디 실수 ....SQL Server 테이블에 Excel 시트에서 데이터를 가져 오는 방법?

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

Excel에서 LINQ로 처리하면 상당한 금액을 절약 할 수 있습니다. http://code.google.com/p/linqtoexcel/ – James

답변

0

왜 MS SQL Server 가져 오기 및 내보내기 마법사 .. 를 사용하지 말아 그것은 가장 쉬운 방법입니다.

이 URL을 올리시면 exect 아이디어를 얻을 수 있습니다. Click Here to View

+0

나는 OP가이 작업을 수행하기 위해 자동화 된 프로세스/실행 파일을 만들고 싶어한다고 생각합니다. –

1

excelConnectionString = @ "공급자 = Microsoft.Jet.OLEDB.4.0; 데이터 원본 = + path + , 속성 = 엑셀 확장 8.0 지속 보안 정보 = 거짓"... 당신을 도움이되기를 바랍니다; 직접 path를 사용하고 여기에

, 당신이 오피스 서버에 설치하지 않아도 당신이 연결 문자열에있는 공급자를 찾을 수 없습니다 찾을 수 있습니다 경우

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

을 다음과 같이 excelConnectionString을 수정 ...

Provider=Microsoft.Jet.OLEDB.4.0; 

Provider=Microsoft.ACE.OLEDB.12.0 

불운하지만 마이크로 소프트는 자신의 서버에 Office를 실행하는 별도의 지불 서버 호스트없이 작동하도록 설계되지 않습니다.