1. 程式人生 > >C#讀取EXL中的數據步驟案例

C#讀取EXL中的數據步驟案例

adapter source ati 路徑 open rgs ace collect ons

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();
}
}
}

C#讀取EXL中的數據步驟案例