Recently, the project needs to study the import and export of Execl.
This project generates another Execl from the data of one Execl, so I didn't use the database. -- Ps: It seems that Execl is also a database! Region ~
First, import Execl to DataSet
Import I selected the OLEDB connection method
The first step is to reference the namespace.
System. Data. OleDb;
Connect Execl
Code Try
{
// Use OleDbConnectionStringBuilder object to construct the connection string.
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder ();
ConnectionStringBuilder. DataSource = @ "" + textBox1.Text; // textBox1.Text select the Execl file path + file name to be imported
ConnectionStringBuilder. Provider = "Microsoft. Jet. OLEDB.4.0 ";
ConnectionStringBuilder. Add ("Extended Properties", "Excel 8.0 ");
Using (OleDbConnection cn = new OleDbConnection (connectionStringBuilder. ConnectionString ))
{
Ds = new DataSet ();
OleDbCommand omd = new OleDbCommand (string. Format ("select * from [{0}]", comboBox1.Text), cn );
OleDbDataAdapter oda = new OleDbDataAdapter (omd );
Oda. Fill (ds );
DataGridView1.DataSource = ds. Tables [0];
}
}
Catch (Exception)
{
MessageBox. Show ("an exception occurred when connecting to Excel. Please check the background code! ");
}
To allow users to select different Sheet tables in the project, read the Sheet in Execl.