2012-12-05 4 views
0

OleDb를 사용하여 datagridview에서 SQL Server 데이터베이스에 Excel 시트를 삽입하려고합니다.SQL Server 데이터베이스에 Excel 시트 삽입

내가 사용하는 코드 :

namespace importfromexcel 
{ 
    public partial class Form1 : Form 
    { 
    SqlConnection conn = new SqlConnection("Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True"); 
    // SqlCommand cmd; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    OpenFileDialog ofd = new OpenFileDialog(); 

    private void button2_Click(object sender, EventArgs e) 
    { 
     if (ofd.ShowDialog() == DialogResult.OK) 
     { 
      textBox1.Text = ofd.FileName; 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;data source=" + ofd.FileName + @";Extended Properties=Excel 8.0;"; 
     // Create Connection to Excel Workbook 

     //We can Import excel to sql server like this 
     using (OleDbConnection connection = new OleDbConnection(excelConnectionString)) 
     { 
      OleDbCommand command = new OleDbCommand("Select fname,lname FROM [sheet1$]", connection); 

      connection.Open(); 

      // Create DbDataReader to Data Worksheet 
      using (DbDataReader dr = command.ExecuteReader()) 
      { 
       // SQL Server Connection String 
       string sqlConnectionString = "Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True"; 
       // SqlCommand cmd; 

       // Bulk Copy to SQL Server 
       using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) 
       { 
        bulkCopy.DestinationTableName = "test"; 
        bulkCopy.WriteToServer(dr); 
       } 
      } 
     } 
    } 
    } 
} 

내 데이터베이스 이름은 다음과 같습니다 mohammed 및 테이블 이름은 두 개의 열 firstnamelastname 및 엑셀 시트 열 fnamelname이다와 test입니다 ..

문제는 내가 코드를 실행하고 button2에서 Excel 시트를 삽입 한 후 button1을 클릭하면 창 오류가 발생합니다.

,

vshot32-clr2.exe은

어떤 도움 작동이 중지되었습니다하세요?

+2

사용자가 원하는 것입니까 아니면 그냥 원하는 것입니까? 그것은 단지 당신을위한 경우 다음 관리 스튜디오를 사용하여 시트를 가져올 수 있습니다. 훨씬 쉽게. –

답변

0

그것이 근본 원인인지는 확실치 않지만 대화 상자에 올바른 파일이 선택되었다고 보장 할 수없는 경우 Click 이벤트에서 ofd.FileName을 참조하고있는 것입니다. 텍스트 상자에 그 값을 저장하고 있기 때문에 나는 그것을 바꿀 것 :

string excelConnectionString = 
    @"Provider=Microsoft.Jet.OLEDB.4.0;data source=" 
      + textBox1.Text 
      + @";Extended Properties=Excel 8.0;"; 

나는 또한 당신이 같은 쿼리 (텍스트 파일로 작성하여 예) 데이터에 수 있는지 확인하는 것입니다 대량 복사를 구현하기 전에 테스트하십시오. 또한 ColumnMapping을 제공하지 않으면 원본 데이터가 정확히 동일한 구조 (열 순서 포함)를 가져야 함을 유의하십시오.

0

SQL 서버에는 SQL Server 데이터 도구라는 가져 오기 도구가 있습니다 ... 거기에서 Excel 파일을 가져올 활동을 찾을 수 있습니다 ... 매우 "최종 사용자"거래로 모든 것을 구성 할 수 있습니다. 끌어서 놓기 기준으로 ...

0

Excel 연결 문자열의 확장 속성에서 HDR = YES 및 IMEX = 1로 설정할 수 있습니다. HDR = YES는 Excel 시트의 첫 번째 행을 읽고 각 셀에 저장된 데이터를 열 이름으로 읽습니다. IMEX = 1은 JET에게 각 셀의 데이터 유형에 관계없이 데이터를 삽입하도록 지시합니다.

내가 작성한이 코드를 한번 보시면 도움이 될 것입니다.

 //ExcelDA Class 
     public ExcelDA() 
    { 
     connString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + ofd.FileName + "; Extended Properties=" + '"' + "Excel 8.0; HDR=Yes; IMEX=1" + '"'; 
    } 

    /// <summary> 
    /// Method used to retrieve a datatable from excel sheet 
    /// </summary> 
    public DataTable GetProductsExcel() 
    { 
     StringBuilder excBuilder = new StringBuilder(); 
     excBuilder.Append("SELECT * FROM [Sheet1$];"); 
     // 
     try 
     { 
      return ExecuteSqlStatement(excBuilder.ToString()); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("Error retreiving data"); 
      return null; 
     } 
    } 
    private DataTable ExecuteSqlStatement(string command) 
    { 
     using (OleDbConnection conn = new OleDbConnection(connString)) 
     { 
      try 
      { 
       conn.Open(); 
       using (OleDbDataAdapter adaptor = new OleDbDataAdapter(command, conn)) 
       { 
        DataTable table = new DataTable(); 
        adaptor.Fill(table); 
        return table; 
       } 
      } 
      catch (SqlException e) 
      { 
       throw e; 
      } 
     } 
    } 
    //SqlDA class 
    public void ExecuteSQLCommand(string comm) 
    { 
     try 
     { 
      using (SqlConnection conn = new SqlConnection(_connectionString)) 
      { 
       conn.Open(); 

       using (SqlCommand command = new SqlCommand(comm, conn)) 
       { 
        command.ExecuteNonQuery(); 
       } 
      } 
     } 
     catch (ArgumentOutOfRangeException ex) 
     { 
      throw ex; 
     } 

     catch (ArgumentException ex) 
     { 
      throw ex; 
     } 
     catch (SqlException ex) { throw ex; } 
    } 
    public void AddNames(string fName, string sName) 
    { 
      StringBuilder sqlQuery = new StringBuilder(); 
      //build sql insert statement here 
      ExecuteSQLCommand(sqlBuilder.ToString()); 
    } 

    //Program class 
    ExcelDA reader = new ExcelDA(); 
    DataTable names = reader.GetSuppliersExcel(); 
    //string array to store excel row data for names 
    string[] arr2 = new string[2] { "", ""}; 
     //recursive loop to retrieve each row and values from each rows columns 
     foreach (DataRow row in suppliers.Rows) 
     { 
      for (int i = 0; i < names.Columns.Count; i++) 
      { 
       if (i == (names.Columns.Count - 1)) 
       { 
        arr2[i] = (row[i].ToString()); 
       } 
       else 
       { 
        arr2[i] = (row[i].ToString()); 
       } 
      } 
     } 

      try 
      { 
       sql.AddNames(arr2[0], arr2[1]); 
       Console.WriteLine("Added Data to SQL"); 
      } 
      catch (Exception) { } 
+0

도움을 주셔서 감사합니다,하지만 같은 오류가 나에게 디버깅 할 때마다 표시됩니다. –