[英]C# How to save textbox info in excel specific rows?
我在程序debug文件夹中放置了一个Excel文档,例如C#project / bin / debug。
我有2个文本框和保存按钮的WinForm。 例如,用户必须在textbox1中输入他的名字,在texbox2中输入他的姓氏,然后单击保存将其保存。
我的问题是,当用户单击“保存”时,如何使textbox1输入保存在excel中的A2行中以及textbox2输入保存在B2行中?
excel文档应该不可见,并且应该在用户点击保存后自动保存文档。
谁能帮我? 代码示例或指南链接将非常有用。
您可以使用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.