C# .NET - how to save form textbox value into exel.

Asked By situ singh on 04-Mar-11 07:14 AM
how to save form textbox value into exel.
in c#.net
Reena Jain replied to situ singh on 04-Mar-11 07:25 AM

here is simple code if you want to save multiple data in excel file

List<int> myList = new List<int>();
ExcelFileWriter<int> myExcel = new ExcelWrite();

if you want to insert more data, I will suggest you to go with this code

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
namespace ExcelAutomation
  class ExcelDB
    string connectionString = string.Empty;
    DbProviderFactory dbFactories = DbProviderFactories.GetFactory("System.Data.OleDb");
    DbConnection con;
    //Constructor which will intialize the connection String
    // The connectivity used here is Generic Database class
    // Using the namespace System.Data.Common
    // We can connect to different database
    // Here I am specifying System.Data.OleDb
    public ExcelDB()
      con =  dbFactories.CreateConnection();
      string dbPath = AppDomain.CurrentDomain.BaseDirectory + "Demo.xls";
      connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbPath + ";Extended Properties='Excel 8.0;HDR=YES'";
      con.ConnectionString = connectionString;
    public int SaveCity(string Name, string Mobile)
        using (DbCommand cmdInsert = con.CreateCommand())
          string commandText= "INSERT INTO [Contacts$]([Name],[Mobile]) VALUES(@name,@mobile)";
          DbParameter param = cmdInsert.CreateParameter();
          param.ParameterName = "@name";
          param.DbType = System.Data.DbType.String;
          DbParameter param1 = cmdInsert.CreateParameter();
          param1.ParameterName = "@mobile";
          param1.DbType = System.Data.DbType.String;
          cmdInsert.CommandText = commandText;
          cmdInsert.Parameters["@name"].Value = Name;
          cmdInsert.Parameters["@mobile"].Value = Mobile;
          return 0;
      catch(Exception ex)
        throw ex;
private void btnsave_Click(object sender, EventArgs e)
      ExcelDB db = new ExcelDB();
      db.SaveCity(txname.Text.Trim(), txmobile.Text.Trim());
      txnew.Text = "";
      txold.Text = "";
      MessageBox.Show("Saved Successfully");

hope this will help you