我正在尝试从函数返回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
}
}但是这个错误会发生
无法将“d__0”类型的对象强制转换为“System.Data.SqlClient.SqlDataReader”类型
解决这个问题的办法是什么?用它作为读者对象的任何选择..。
发布于 2013-10-15 15:17:43
您正在返回一种类型的IEnumerable<IDataRecord>,因此不能将其转换为SqlDataReader。
只要返回xlsReader (确保正确地释放它),如果这是您想要的。否则,只需使用您要返回的数据。
https://stackoverflow.com/questions/19384823
复制相似问题