对Excel的操作时很频繁的,用哪种方法更合适,那就看系统的应用了。下面应用odbc读写Excel特别方便、简单。便随笔随笔更多好方法还望高手留笔
首先当然要引用using System.Data.Odbc 名称空间。
具体读Excel方法:
1 OdbcConnection Connnection = new OdbcConnection();
2 Connnection.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};DBQ=" + itemFile;
3 OdbcCommand cmd = new OdbcCommand();
4 cmd.Connection = Connnection;
5 cmd.CommandText = "SELECT * FROM [Sheet1$]";
6 OdbcDataAdapter oda = new OdbcDataAdapter(cmd);
7 DataTable dt = new DataTable();
8 oda.Fill(dt);
9 Connnection.Close();
2 Connnection.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};DBQ=" + itemFile;
3 OdbcCommand cmd = new OdbcCommand();
4 cmd.Connection = Connnection;
5 cmd.CommandText = "SELECT * FROM [Sheet1$]";
6 OdbcDataAdapter oda = new OdbcDataAdapter(cmd);
7 DataTable dt = new DataTable();
8 oda.Fill(dt);
9 Connnection.Close();
具体写Excel 方法:
1 OdbcConnection Connnection = new OdbcConnection();
2 Connnection.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};Readonly=0;DBQ=" + itemFile;
3 OdbcCommand cmd = new OdbcCommand();
4 cmd.Connection = Connnection;
5 Connnection.Open();
6 cmd.CommandText="Insert into [Sheet1$] (name,password) values ('admin','admin')";
7 cmd.ExecuteNonQuery();
8 Connnection.Close();
2 Connnection.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};Readonly=0;DBQ=" + itemFile;
3 OdbcCommand cmd = new OdbcCommand();
4 cmd.Connection = Connnection;
5 Connnection.Open();
6 cmd.CommandText="Insert into [Sheet1$] (name,password) values ('admin','admin')";
7 cmd.ExecuteNonQuery();
8 Connnection.Close();
如果更新的话,CommandText值改成Update语句就可以了。
觉得值得注意的地方:执行写操作时,ConnectionString要设置Excel文件可写。