2013-12-22 4 views
-1

데이터 세트에서 파일 데이터를 Excel에서 가져오고 있지만 데이터 세트 데이터가 중복되어 Excel 파일에 네 개의 레코드가 있고 데이터 세트에서 저에게 8 개의 레코드가 표시됩니다. 각 레코드는 중복됩니다. 내 파일 확장자는 .xlsx입니다. 내가 뭘 잘못하고있어? 당신은 두 번 데이터 세트를 작성하는데이터 세트에 중복 레코드가 있습니다

public static DataSet GenerateExcelData(string path) 
    { 
     OleDbConnection oledbConn = null; 
     try 
     { 

      /* connection string to work with excel file. HDR=Yes - indicates 
       that the first row contains columnnames, not data. HDR=No - indicates 
       the opposite. "IMEX=1;" tells the driver to always read "intermixed" 
       (numbers, dates, strings etc) data columns as text. 
      Note that this option might affect excel sheet write access negative. */ 

      if (Path.GetExtension(path) == ".xls") 
      { 
       oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""); 
      } 
      else if (Path.GetExtension(path) == ".xlsx") 
      { 
       //oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"); 
       oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"); 
      } 
      oledbConn.Open(); 
      OleDbCommand cmd = new OleDbCommand(); ; 
      OleDbDataAdapter oleda = new OleDbDataAdapter(); 
      DataSet ds = new DataSet(); 

      cmd.Connection = oledbConn; 
      cmd.CommandType = CommandType.Text; 
      cmd.CommandText = "SELECT * FROM [Sheet1$]"; 
      oleda = new OleDbDataAdapter(cmd); 
      oleda.Fill(ds); 
      //EDIT: Below lines are duplicate 
      //oleda = new OleDbDataAdapter(cmd); 
      //oleda.Fill(ds); 
      return ds; 
     } 
     // need to catch possible exceptions 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      oledbConn.Close(); 
     } 
    } 

답변

1

:

여기 내 코드입니다.

이미 두 줄을 추가했음을 잊었을 수 있습니다. 중복 된 코드 만 삭제하면됩니다.

2

데이터 세트를 두 번 채우고 있습니다.

+0

감사합니다, 네, 이것은 실수입니다. – Sami

2
oleda = new OleDbDataAdapter(cmd); 
oleda.Fill(ds); 

왜이 코드 블록이 두 번 반복됩니까? 이 오류가 발생하는 것 같아요

관련 문제