我想从 Excel 文件 (xlsx) 中读取列并绑定 GridView 中的值。但这会引发以下异常
Microsoft Access 数据库引擎无法打开或写入文件“”。它已被其他用户独占打开,或者您需要权限才能查看和写入其数据。
这个问题的原因是什么?
代码隐藏:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["xlsx"].ConnectionString;
// Create the connection object
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
this.gvExcel.DataSource = ds.Tables[0].DefaultView;
this.gvExcel.DataBind();
}
catch(Exception exc)
{
}
finally
{
// Close connection
oledbConn.Close();
}
}
}
asp代码:
<asp:GridView ID="gvExcel" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>