我正在创建一个小应用程序,将Excel数据导入我的数据库。当我点击按钮时,它会崩溃并显示以下错误信息:
以下是我的代码:
我尝试过在网上搜索和修改代码,但问题仍然存在。我尝试将文件保存为.xls格式,但运行代码后,页面会离线,并显示Google Chrome的“此网页不可用”(甚至无法进入调试)。外部表格格式不符合预期。
以下是我的代码:
string strConnection = ConfigurationManager.ConnectionStrings["---"].ConnectionString;
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "TableName";
sqlBulk.WriteToServer(dReader);
}
}
}
}