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();
}
}
}
aspx コード:
<asp:GridView ID="gvExcel" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>