1

我正在尝试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();
       }

这没关系 It Return 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”类型

该问题的解决方案是什么?将其用作阅读器对象的任何替代方法...

4

1 回答 1

3

您正在返回一种IEnumerable<IDataRecord>,因此您不能将其转换为SqlDataReader

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

于 2013-10-15T15:17:43.360 回答