Button1 is the dynamic creation of excle, button2 is the addition of data, button3 is the real data
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;
Using system. IO;
Namespace connection excle
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Try
{
If (file. exists ("F: \ example.xls "))
File. Delete ("F: \ example.xls ");
Using (oledbconnection conn = new oledbconnection ("provider = Microsoft. Jet. oledb.4.0; Data Source = F: \ example.xls; extended properties = 'excel 8.0; HDR = Yes '"))
{
Conn. open ();
Oledbcommand cmd = new oledbcommand ("create table booksheet1 ([x] int, [y] int, [Z] INT)", Conn );
Cmd. executenonquery ();
MessageBox. Show ("excle created ");
}
}
Catch (system. Exception)
{
MessageBox. Show ("error ");
}
}
Private void button2_click (Object sender, eventargs E)
{
String connstring = "provider = Microsoft. Jet. oledb.4.0; Data Source = F: \ example.xls; extended properties = 'excel 8.0; HDR = Yes '";
Oledbconnection conn = new oledbconnection (connstring );
String commandstring = "select * from [booksheet1]";
Oledbdataadapter adapter = new oledbdataadapter (commandstring, Conn );
Oledbcommandbuilder Cd = new oledbcommandbuilder (adapter );
Dataset DS = new dataset ();
Try
{
Conn. open ();
Adapter. Fill (DS, "ww ");
Datarow new_row1 = Ds. Tables ["ww"]. newrow ();
New_row1 ["X"] = 3;
New_row1 ["Y"] = 4;
New_row1 ["Z"] = 5;
DS. Tables ["ww"]. Rows. Add (new_row1 );
Datarow new_row2 = Ds. Tables ["ww"]. newrow ();
New_row2 ["X"] = 6;
New_row2 ["Y"] = 7;
New_row2 ["Z"] = 8;
DS. Tables ["ww"]. Rows. Add (new_row2 );
Adapter. Update (DS, "ww ");
Conn. Close ();
MessageBox. Show ("data added successfully ");
}
Catch (system. Exception)
{
MessageBox. Show ("error ");
}
}
Private void button3_click (Object sender, eventargs E)
{
String connstring = "provider = Microsoft. Jet. oledb.4.0; Data Source = F: \ example.xls; extended properties = 'excel 8.0; HDR = Yes '";
Oledbconnection conn = new oledbconnection (connstring );
String commandstring = "select * from [booksheet1]";
Oledbdataadapter adapter = new oledbdataadapter (commandstring, Conn );
Dataset DS = new dataset ();
Adapter. Fill (DS, "ww ");
Datagridview1.datasource = new dataview (Ds. Tables ["ww"]);
}
}
}