从Excel文件绑定GridView会引发权限异常

时间:2013-06-15 11:32:44

标签: c# asp.net excel

我想从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>

0 个答案:

没有答案