Excel操作
1.使用OLEDB操作Excel
關於OLEDB介紹參考
http://www.cnblogs.com/moss_tan_jun/archive/2012/07/28/2612889.html
2.連接字符串
舊版本
"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
新版本
"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
Program.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelOperate
{
class Program
{
static void Main(string[] args)
{
string connectStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "裝備信息.xls" + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
//1.創建連接到數據源對象
OleDbConnection connection = new OleDbConnection(connectStr);
//2.打開連接
connection.Open();
//3.查詢得到數據
string sql = "select * from [Sheet1$]";//這是一個查詢命令
OleDbDataAdapter adapter = new OleDbDataAdapter(sql,connection);
DataSet dataSet = new DataSet();//用來存放數據,存放datatable
adapter.Fill(dataSet);//表示把查詢的結果(datatable對象)放到(填充)dataset裏面
//4.關閉連接
connection.Close();
//5.取得數據
DataTableCollection tableCollection = dataSet.Tables;//獲得當前集合中所有的表格
DataTable table = tableCollection[0];//因爲我們就存放了一張表格,這裏取得索引爲0的表格就是我們剛剛查詢到的表格
//6.取得表格中的數據
//取得table的所有行
DataRowCollection rowconnection = table.Rows;//返回一一個行的集合
//遍歷行的集合,取得每一個行的dataRow對象
foreach (DataRow row in rowconnection)
{
//取得row中前八列的數據,索引0-7
for (int i = 0; i < 8; i++)
{
Console.Write(row[i]+" ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
裝備信息.xls
運行截圖