我正在研究一个 asp.net,我必须将所有 Excel 数据放入 SQL Server 表中。为此,我使用了文件上传来上传 Excel 文件,并在单击按钮时将 Excel 的所有数据插入 SQL Server 2008。在单击按钮时,我使用了以下代码:
protected void ImportNow_Click(object sender, EventArgs e)
{
private static string _connStr = System.Configuration.ConfigurationManager.AppSettings["Database1"].ToString();
try
{
if ((fileuploadExcel.FileName != ""))
{
string extension = Path.GetExtension(fileuploadExcel.PostedFile.FileName);
string excelConnectionString;
SqlConnection conn = new SqlConnection(_connStr);
string tableName = "School";
string path = fileuploadExcel.PostedFile.FileName;
//Create connection string to Excel work book
if (extension == ".xls")
{
excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
";Extended Properties=Excel 8.0;Persist Security Info=False";
}
else
{
excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path +
";Extended Properties=Excel 12.0;Persist Security Info=False";
}
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
conn.Open();
SqlCommand comm = new SqlCommand("truncate table " + tableName, conn);
SqlCommand identityChange = conn.CreateCommand();
identityChange.CommandText = "SET IDENTITY_INSERT " + tableName + " ON";
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
identityChange.ExecuteNonQuery();
SqlBulkCopy sqlBulk = new SqlBulkCopy(_connStr);
//Give your Destination table name
sqlBulk.DestinationTableName = tableName;
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
conn.Close();
lblMessage.ForeColor = Color.Green;
lblMessage.Text = "Import into table <b>" + tableName + "</b> successful!<br />";
}
else
{
lblMessage.ForeColor = Color.Red;
lblMessage.Text = "Please first upload (Select) excel file.";
}
}
catch (Exception ex)
{
throw (ex);
}
}
当我上传 Excel 文件并阅读它时,它会显示错误
Microsoft Office Access 数据库引擎找不到对象“Sheet1$”。确保对象存在并且正确拼写其名称和路径名。
即使有一个文件具有Sheet1
. 请帮我。谢谢