【发布时间】:2014-10-15 14:18:05
【问题描述】:
我正在开发一个 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 的文件。请帮我。谢谢
【问题讨论】:
-
这很可能与文件相对于代码的位置有关。这是上传的文件吗?还要确保 ASP 进程有足够的权限来查看文件。
-
是的,这是一个上传的文件。
-
那很可能是权限问题。
-
没有它有读取权限