In this blog, I will show how add data in excel sheet using c# and view the data in excel using GridView by selecting the data in the GridView.
- Create an excel file locally (location is local).
- Now create a form with the GridView, 2 text boxes and a command button like the following form:
- Here's the code in the form load event:
- String filename=@"D:\dem.xlsx";
- String connection=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filename+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
- String Command="Select * from [sheets$]";
- OleDbConnection con=new OleDbConnection(connection);
- con.Open();
- OleDbCommand cmd=new OleDbCommand(Command,con);
- OleDbDataAdapter db=new OleDbDataAdapter(cmd);
- DataTable dt=new DataTable();
- db.Fill(dt);
- dataGridView1.DataSource=dt;
This code allow us to load the existing excel data into the GridView.
- Add the following code in the command button to add the values in the excel sheet.
- String filename=@"D:\dem.xlsx";
- String connection=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filename+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
- String Command="insert into [sheets$](Name,age) values('"+this.textBox1.Text+"','"+this.textBox2.Text+"')";
- OleDbConnection con=new OleDbConnection(connection);
- con.Open();
- OleDbCommand cmd=new OleDbCommand(Command,con);
- cmd.ExecuteNonQuery();
- loaddata();
- Add the following code in the command button to update the values in the excel sheet.
- String filename=@"D:\dem.xlsx";
- String connection=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+filename+";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
- String Command="update[sheets$] set age='"+textBox2.Text+"' where Name='"+textBox1.Text+"';";
- OleDbConnection con=new OleDbConnection(connection);
- con.Open();
- OleDbCommand cmd=new OleDbCommand(Command,con);
- cmd.ExecuteNonQuery();
- loaddata();
- Add the following line of code. This code help us to view the grid view data in textboxes.
- DataGridViewRow rows=this.dataGridView1.Rows[e.RowIndex];
- textBox1.Text=rows.Cells["Name"].Value.ToString();
- textBox2.Text=rows.Cells["age"].Value.ToString();
- Deletion is not possible in excel through OLEDB. For more details refer the link.
Have fun….!!! Happy coding