1

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

0 回答 0