简体   繁体   English

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

[英]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. 我在程序debug文件夹中放置了一个Excel文档,例如C#project / bin / debug。

I have WinForm with 2 text boxes, and save button. 我有2个文本框和保存按钮的WinForm。 User must input for example his name in textbox1 and his surname in texbox2 and save it by clicking save. 例如,用户必须在textbox1中输入他的名字,在texbox2中输入他的姓氏,然后单击保存将其保存。

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? 我的问题是,当用户单击“保存”时,如何使textbox1输入保存在excel中的A2行中以及textbox2输入保存在B2行中?

The excel document should not be visible and it should auto save document after user hits save. excel文档应该不可见,并且应该在用户点击保存后自动保存文档。

Can anyone help me? 谁能帮我? Code samples or links to guides would be very usefull. 代码示例或指南链接将非常有用。

You can work with Excel files using OleDb objects. 您可以使用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();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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