标签:asp.net command apt and sele VID .net 方式 creat
来自森大科技官方博客 http://www.cnsendblog.com/?p=84String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=c:/test.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM [sheet1]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
//将Excel中数据填充到数据集
objAdapter1.Fill(objDataset1, "XLData");
objConn.Close();
从上面可以看出,使用ADO.NET可将Excel当作普通数据库,使用SQL语句来操作。
通过ADO.NET获取Excel文件的各Sheet名称,可使用元数据方式:
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=c:/test.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cn = new OleDbConnection(sConnectionString);
cn.Open();
DataTable tb = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow row in tb.Rows)
{
//遍历弹出各Sheet的名称
MessageBox.Show(row["TABLE_NAME"]);
}
关于使用ADO.NET创建并写入Excel文件与普通数据库操作极为类似,参见以下代码:
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=c:/test.xls;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cn = new OleDbConnection(sConnectionString);
string sqlCreate = "CREATE TABLE TestSheet ([ID] INTEGER,[Username] VarChar,[UserPwd] VarChar)";
OleDbCommand cmd = new OleDbCommand(sqlCreate, cn);
//创建Excel文件:C:/test.xls
cn.Open();
//创建TestSheet工作表
cmd.ExecuteNonQuery();
//添加数据
cmd.CommandText = "INSERT INTO TestSheet VALUES(1,‘elmer‘,‘password‘)";
cmd.ExecuteNonQuery();
//关闭连接
cn.Close();
Asp.Net(C#)使用oleDbConnection 连接Excel
标签:asp.net command apt and sele VID .net 方式 creat
原文地址:http://blog.51cto.com/14036626/2309812