2013-10-15 2 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를 돌려 OK입니다를 작성하고 I가 발생할

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 (올바르게 처분해야합니다). 원하는 경우에만 반환하십시오. 그렇지 않으면 반환 할 데이터 만 사용하십시오.