Insert records to excel

In this blog we will know how to insert records to excel.

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.OleDb;

 

namespace Insert_data_into_excel

{

    public partial class Form1 : Form

    {

        OleDbConnection con;

        OleDbCommand com;

        string str;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_add_Click(object sender, EventArgs e)

        {

            try

            {

 

                com = new OleDbCommand();

                con = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='d:\\test.xls';Extended Properties=Excel 8.0;");

                con.Open();

                com.Connection = con;

                str = "Insert into [sheet1$] (Name) values('" + textBox1.Text + "')";

                com.CommandText = str;

                com.ExecuteNonQuery();

                con.Close();

                MessageBox.Show("Records Added Successfully");

                textBox1.Text = "";

                textBox1.Focus();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

           

        }

    }

}