C#如何在excel特定行中保存文本框信息?

时间:2012-05-15 16:32:00

标签: c#

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

我有两个文本框的WinForm和保存按钮。用户必须在textbox1中输入他的名字,在texbox2中输入他的姓氏,然后点击保存即可保存。

我的问题是如何在excel和textbox2输入中将textbox1输入保存到第A2行,以便在用户单击保存时保存在第B2行?

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

任何人都可以帮助我吗?代码示例或指南链接非常有用。

1 个答案:

答案 0 :(得分: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();
            }
        }
    }
}