我正在尝试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”类型
该问题的解决方案是什么?将其用作阅读器对象的任何替代方法...