Csharp不能使用oledb读取excel

我正在尝试使用Visual Studio本地主机从.aspx页面读取Excel文件。 我将Excel保存在根文件夹中,但试图读取它时,显示以下exception:

Microsoft Office Access数据库引擎无法打开或写入文件“”。 它已经由另一个用户专门打开,或者您需要查看和写入其数据的权限。

我的oledb代码

string connString = ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString; OleDbConnection oledbConn = new OleDbConnection(connString); try { // Open connection oledbConn.Open(); // Create OleDbCommand object and select data from worksheet Sheet1 OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn); // Create new OleDbDataAdapter OleDbDataAdapter oleda = new OleDbDataAdapter(); oleda.SelectCommand = cmd; // Create a DataSet which will hold the data extracted from the worksheet. DataSet ds = new DataSet(); // Fill the DataSet from the data extracted from the worksheet. oleda.Fill(ds, "Employees"); // Bind the data to the GridView GridView1.DataSource = ds.Tables[0].DefaultView; GridView1.DataBind(); } catch(Exception ex) { throw ex; } finally { // Close connection oledbConn.Close(); } 

连接string

 <connectionStrings> <add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ExcelToParse.xls;Extended Properties=Excel 8.0"/> <add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=ExcelToParse.xlsx;Extended Properties=Excel 12.0"/> </connectionStrings> 

有人可以指出我在这里做错了吗?

首先在命令提示符下运行这个命令来终止所有打开的Excel进程。

 taskkill /f /im excel.exe 

您需要处理连接对象。 然后在你的finally块中改变你的代码 –

 finally { // Close connection oledbConn.Close(); oledbConn.Dispose(); System.Runtime.InteropServices.Marshal.ReleaseComObject(oledbConn); } 

请让我知道,如果它的工作。