OleDbDataReader cmd.ExecuteReader() “Enumeration Yielded No



>我试图从excel文件中获取数据并将其设置为数据库中

我的代码看起来像这个答案

var path = GetPath(activityId);
path = Path.Combine(path, fileName);
var strConnection = GetConnectionString();
var excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0"", path);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
excelConnection.Open();
DataTable dtSchema = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string firstSheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
using (OleDbCommand cmd = new OleDbCommand("Select * from [" + firstSheetName + "]" , excelConnection))
{
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = tableName;
while (dReader.Read())
{
sqlBulk.WriteToServer(dReader);
}
}
}
}

但是当我调试sqlBulk.WriteToServer(dReader);时,我显示此错误,数据也没有加载到表中:

空 ="枚举未产生任何结果">

我尝试了很多答案,但没有成功

注意:我上传的 excel 字段和我的表格看起来相同

我通过更改我的代码来解决此问题,如下所示(使用OleDbDataAdapter而不是OleDbDataReader(:

DataTable Contents = new DataTable();
using (OleDbDataAdapter cmd = new OleDbDataAdapter("Select * from [" + firstSheetName + "]", excelConnection))
{
cmd.Fill(Contents);
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = tableName;
sqlBulk.WriteToServer(Contents);
}
}

相关内容

  • 没有找到相关文章

最新更新