string fileName = "装备信息.xls";
// xls
string commandString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
// xlsx
string commandString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
// 创建连接到数据源的对象
OleDbConnection command = new OleDbConnection(commandString);
// 打开连接
command.Open();
// Sql的查询命令,有关于数据库自行百度或者Google
string sql = "select * from [Sheet1$]";
OleDbDataAdapter adaper = new OleDbDataAdapter(sql,command);
// 用来存放数据
DataSet dataSet = new DataSet();
// 填充DataTable数据到DataSet中
adaper.Fill(dataSet);
// 释放连接的资源
command.Close();
// 取得数据
DataTableCollection tableCollection = dataSet.Tables; //获取当前集合中的所有表格
//只取第一张表格,因为只有一张
DataTable table = tableCollection[0];
// 获取表格中的数据
// 取表格table中的所有行
DataRowCollection rowCollection = table.Rows;//返回一行的数据
// 遍历行的集合,取得每一行的datarow数据
foreach (DataRow row in rowCollection) {
// 取table中的列数
for (int i = 0; i < table.Columns.Count; i++) {
// 遍历数据
Console.Write(row[i]+" ");
}
Console.WriteLine();
}
Console.ReadKey();
以上就是Excel的查询很简单,不做太多讲诉。