2013-12-22 91 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

您填寫兩次數據集。

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

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

您可能忘記了您已經添加了兩行。你只需要刪除重複的代碼。

2

您正在填充數據集兩次。

+0

謝謝,是的,這是錯誤的。 – Sami

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

爲什麼這段代碼重複兩次?我認爲這是導致錯誤