//使用数据库方式建立连接
string fileName = "装备信息.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//xls "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//xxls "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection connection = new OleDbConnection(connectionString);
//打开连接
connection.Open();
//查询命令
string sql = "select * from [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connection);
//用来存放数据
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);//表示把查询的结果(datatable)填充到dataset中
connection.Close();//关闭连接
//取数据
//获得dataSet中所有的table
DataTableCollection dataTableCollection = dataSet.Tables;
//获取被存入在其中的第几个表格
DataTable dataTable = dataTableCollection[0];
//取得表格中的所有行
DataRowCollection dataRowCollection = dataTable.Rows; //返回行的集合
//遍历行的集合,取得每一个行的datarow对象
foreach (DataRow row in dataRowCollection )
{
//取得row中前八列的数据, 索引0-7
for (int i = 0; i < 8; i++)
{
Console.Write(row[i]+"");
}
Console.WriteLine();
}
Console.ReadLine();
C#中的EXCEL操作
最新推荐文章于 2019-04-09 16:56:16 发布