Search

Modify Excel file using c#

using System;
using System.Data;
using System.Data.OleDb ;

public partial class _Default : System.Web.UI.Page
{
 protected void Button1_Click(object sender, EventArgs e)
 {
  try
  {
   string connStr = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='your-excel-file.xls';Extended Properties=Excel 8.0;";
   OleDbConnection MyConnection;
   OleDbCommand MyCommand = new OleDbCommand();
   MyConnection = new OleDbConnection(connStr);

   MyConnection.Open();
   MyCommand.Connection = MyConnection;
   string sql = "Update [Sheet1$] set name = 'New Name' where id=1";
   MyCommand.CommandText = sql;
   MyCommand.ExecuteNonQuery();
   MyConnection.Close();

   Label1.Text = "data updated successfully !! ";
  }
  catch (Exception ex)
  {
   Label1.Text = ex.ToString();
  }
 }
}