using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
namespace Excel操作
{
class Program
{
static void Main(string[] args)
{
//excel文件路径
string fileName = @"d:\文档\visual studio 2017\Projects\MyTest\Excel操作\装备信息.xls";
//连接字符串
//,xls后缀时用以下连接字符串
// "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//.xlsx后缀时用以下连接字符串
// "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//连接oledb
OleDbConnection connetction = new OleDbConnection(connectionString);
connetction.Open();
//查询语句
string sql = "select * from [Sheet1$]";
//将查询结果放入adapter数据适配器中
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connetction);
//建立一个空的Dataset数据集
DataSet dataSet = new DataSet();
//将adapter中的数据Fill到dataSet中
adapter.Fill(dataSet);
//关闭连接,此时查询结果数据已经在dataset中了
connetction.Close();
//取得dataSet中的tables集合
DataTableCollection tableCollection = dataSet.Tables;
//取得第一张table
DataTable table = tableCollection[0];
//取得table中的所有row
DataRowCollection rowCollection = table.Rows;
//遍列所有row中的信息(不括标题字段)
foreach (DataRow row in rowCollection)
{
for (int i = 0; i < 8; i++)
{
Console.Write(row[i] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}