2013-12-22 57 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); 

为什么这段代码重复两次?我认为这是导致错误