从函数返回OleDbDataReader

时间:2013-10-15 15:12:13

标签: c# sql-server asp.net-mvc-4

我正在尝试从函数返回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,我试图通过

抓住这个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
        }
   }

但错误发生

  

无法将“d__0”类型的对象强制转换为类型   'System.Data.SqlClient.SqlDataReader'

该问题的解决方案是什么?任何使用它作为读者对象的替代方案......

1 个答案:

答案 0 :(得分:3)

您将返回IEnumerable<IDataRecord>类型,因此无法将其投放到SqlDataReader

如果这是您想要的,只需返回xlsReader(确保妥善处理)。否则,只需使用您要返回的数据。