[英]Csharp Not able to read excel using oledb
我试图使用Visual Studio本地主机从.aspx页读取Excel文件。 我将Excel保留在根文件夹中,但是在尝试读取它时,它显示以下异常:
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();
}
连接字符串
<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);
}
请让我知道它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.