简体   繁体   中英

C# How to save textbox info in excel specific rows?

I have an excel document placed in programs debug folder, example C# project/bin/debug.

I have WinForm with 2 text boxes, and save button. User must input for example his name in textbox1 and his surname in texbox2 and save it by clicking save.

My question is how can I make textbox1 input to save in row A2 in excel and textbox2 input to save in row B2 when user clicks save?

The excel document should not be visible and it should auto save document after user hits save.

Can anyone help me? Code samples or links to guides would be very usefull.

You can work with Excel files using OleDb objects.

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();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM