首页 > 解决方案 > 通过 asp.net 应用程序将值插入 excel

问题描述

我有一个电子表格需要接受来自 asp.net 应用程序的数据。

我写了一些 c#,允许我从另一个电子表格中读取数据,但现在我想从文本框中输入一些数据。

        protected void Button2_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection();
        string path = Server.MapPath("LOG_TEST.xlsx");
        String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;IMEX=1;'";
        conn.ConnectionString = connString;
        conn.Open();
        OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sheet1$] ([NAME], [MOBILE], [EMAIL]) VALUES('" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')",conn);
        OleDbDataReader rd = cmd.ExecuteReader();
        conn.Close();
    }

只需将 3 个值插入电子表格即可。

我得到的错误如下。

在此处输入图像描述

我相信问题就在身边

OleDbDataReader rd = cmd.ExecuteReader();

但不确定用什么替换它。

标签: c#asp.netexcelinsert

解决方案


我建议像下面那样简化它:使用本地驱动器 C: 中的电子表格,更新connString. 在您的 INSERT QUERY 中使用字符串值,您可以稍后对其进行更新。我们只是想确保它首先起作用!顺便说一句,我没有测试这段代码,但我认为它应该可以工作。

protected void Button2_Click(object sender, EventArgs e)
{
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\SPECIFY HERE\\LOG_TEST.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";

 string query ="INSERT INTO [Sheet1$] (NAME, Mobile, Emails) VALUES ('Bob', '1', 'Whatever@mail')";

 OleDbConnection con = new OleDbConnection(connString);
 OleDbCommand cmd = new OleDbCommand(query, con);

 con.Open();
 cmd.ExecuteNonQuery();


}

我假设您可以编写一个函数来打开您的 excel 文件,例如

//Make sure you add these two references. 
using Microsoft.Office.Interop
using Excel = Microsoft.Office.Interop.Excel

//Call this before your insert
static void FileOpen() {
    string path = "Path.xlsx"
    var excel = new Excel.Application
    excel.Visible=True

    Excel.Workbooks books = excel.Workbooks;
    Excel.Workbook sheet = books.Open(path);
}

推荐阅读