0

我在程序调试文件夹中放置了一个 excel 文档,例如 C# project/bin/debug。

我有带 2 个文本框的 WinForm 和保存按钮。例如,用户必须在 textbox1 中输入他的姓名,在 texbox2 中输入他的姓氏,然后通过单击保存来保存。

我的问题是,当用户单击保存时,如何使 textbox1 输入保存在 Excel 的 A2 行中,以及如何使 textbox2 输入保存在 B2 行中?

excel 文档不应该是可见的,它应该在用户点击保存后自动保存文档。

谁能帮我?代码示例或指南链接将非常有用。

4

1 回答 1

0

您可以使用 OleDb 对象处理 Excel 文件。

using System;
using System.Data;
using System.Data.OleDb;

public static class Program
{
    ///This is a very basic example of how to use OleDb objects to edit spreadsheets.
    /// For more advanced operations, look into using OleDb with DataSets/DataTables.
    public static void Main(string[] args)
    {
        string Filename = "C:\\test.xls";
        //If you are using xls format, use this connection string.
        string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Filename + ";Extended Properties=\"Excel 8.0;HDR=NO;\"";
        //If you are using xlsx format, use this connection string.
        //string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO\"";

        string Name_Value = "First Name";
        string Surname_Value = "Surname";

        string SQL1 = "UPDATE [Sheet1$A2:A2] SET F1='" + Name_Value + "'";
        string SQL2 = "UPDATE [Sheet1$B2:B2] SET F1='" + Surname_Value + "'";

        using(OleDbConnection Connection = new OleDbConnection(ConnectionString))
        {
            Connection.Open();
            using(OleDbCommand cmd1 = new OleDbCommand(SQL1,Connection))
            {
                cmd1.ExecuteNonQuery();
            }
            using(OleDbCommand cmd2 = new OleDbCommand(SQL2,Connection))
            {
                cmd2.ExecuteNonQuery();
            }
        }
    }
}
于 2012-05-15T17:00:51.433 回答