如何在ASP.NET中通过ODBC连接插入查询到Excel?

我有这样一个excel文件:

在这里输入图像说明

我有两个TextBox(Fname,Lname),拖动button(Search,Insert)和一个GridView来显示结果。 searchbutton工作正常,但插入button不起作用。

插入button时出错:

ERROR [HY000] [Microsoft][ODBC Excel Driver] Operation must use an updateable query. 

ASPX:

 Fname:<asp:TextBox ID="txtFname" runat="server"></asp:TextBox><br /> Lname:<asp:TextBox ID="txtLname" runat="server"></asp:TextBox><br /> <asp:Button ID="cmdSearch" runat="server" onclick="cmdSearch_Click" Text="Search" /> <asp:Button ID="cmdInsert" runat="server" onclick="cmdInsert_Click" Text="Insert" /><br /> <asp:GridView ID="GridView1" runat="server"></asp:GridView> 

代码后面:

 string conStr = @"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};"+ @"DBQ=|DataDirectory|\q.xlsx;"; protected void cmdInsert_Click(object sender, EventArgs e) { OdbcConnection con = new OdbcConnection(conStr); con.Open(); string query = "insert into [Sheet1$] (Fname,Lname) values (?,?)"; OdbcCommand cmd = new OdbcCommand(query, con); cmd.Parameters.AddWithValue("?",txtFname.Text); cmd.Parameters.AddWithValue("?", txtLname .Text); cmd.ExecuteNonQuery();// has error con.Close(); } protected void cmdSearch_Click(object sender, EventArgs e) { OdbcConnection con = new OdbcConnection(conStr); con.Open(); string query = ""; query = "select * from [Sheet1$] where Fname=? or Lname=?"; OdbcCommand cmd = new OdbcCommand(query, con); cmd.Parameters.AddWithValue("?", txtFname.Text); cmd.Parameters.AddWithValue("?", txtLname.Text); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind(); con.Close(); } 

每个http://support.microsoft.com/kb/316475

确保你添加“ReadOnly = 0”

 string conStr = @"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};"+ @"DBQ=|DataDirectory|\q.xlsx;ReadOnly=0;"; 

使用更像LinqToExcel (你也可以在NuGet中find它)的结构,这是非常容易使用和使用后台的ODBC可以解决错误,或者至less缩小可能的错误。