2013-10-15 35 views
1

返回一個OleDbDataReader我試圖從一個函數返回OleDbDataReader。我搜索互聯網上,我發現了一些幫助,我創建代碼從功能

public IEnumerable<IDataRecord> ImportXLS(string path) 
     { 

      string connString = ""; 
      string strFileType = ".xlsx"; 

      if (strFileType.Trim() == ".xls") 
      { 
       connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; 
      } 
      else if (strFileType.Trim() == ".xlsx") 
      { 
       connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; 
      } 

      string query = "SELECT * FROM [Sheet1$]"; 

      OleDbConnection conn = new OleDbConnection(connString); 
      conn.Open(); 
      OleDbCommand cmd = new OleDbCommand(query, conn); 

      using (IDataReader xlsReader = cmd.ExecuteReader()) 
      { 
       while (xlsReader.Read()) 
       { 
        yield return (IDataReader)xlsReader; 
       } 
      } 

      conn.Close(); 
     } 

這是確定其返回xlsReader,我試圖通過

public string UploadFile(string tPath, string FileName) 
    { 
     string msg = ""; 

     FileImportModule.FileImport OFileImport = new FileImportModule.FileImport(); 
     SqlDataReader reader = (SqlDataReader)OFileImport.ImportXLS(tPath);    
     var context = new MountSinaiEntities1(); 

     string tableName = context.Tables.Find(1).tableName; 
     var tableFieldList = from a in context.TablesFields       
          where a.tableId == 1 
          select a.fieldName;  

     //1- SQL Bulk Copy 
     try 
     { 
      SqlConnection con = new SqlConnection(@"Data Source=abhishek-pc;Initial Catalog=MountSinai;User ID=sa;Password=abhi"); 
      con.Open(); 
      SqlBulkCopy bulkcopy = new SqlBulkCopy(con); 
      { 
       bulkcopy.DestinationTableName = tableName; 
       bulkcopy.WriteToServer(reader); 
      } 
      con.Close(); 
     } 
     catch (Exception e) 
     { 
      //Handle Exception 
     } 
    } 

但錯誤捕獲這個xlsReader發生

無法將類型爲'd__0'的對象轉換爲類型爲 'System.Data.SqlClient.SqlDataReader'

該問題的解決方案是什麼?任何使用它作爲讀者對象的替代方案...

+1

製作'ImportXLS'返回'IDataReader'。不要忘記關閉連接和讀取器(在finally塊中使用(...)或'.Close()')。 –

回答

3

您正在返回一種IEnumerable<IDataRecord>,因此您無法將其轉換爲SqlDataReader

只要返回xlsReader(確保正確處置它),如果這是你想要的。否則,只需使用您要返回的數據。