C#編程 Excel操做

使用OLEDB操做Excel,關於OLEDB介紹參考http://www.cnblogs.com/moss_tan_jun/archive/2012/07/28/2612889.htmlhtml

 

鏈接字符串:一個是後綴爲.xls,一個是.xlsxsql

    "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";   ide

 "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";spa

 

下面來操做這張表:code

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _033_Excel操做 {
    class Program {
        static void Main(string[] args)
        {
            string fileName = "裝備信息.xls";
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.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();//用來存放數據 用來存放DataTable

            adapter.Fill(dataSet);//表示把查詢的結果(datatable)放到(填充)dataset裏面
            
            connection.Close();//釋放鏈接資源

            //取得數據
            DataTableCollection tableCollection= dataSet.Tables;//獲取當前集合中全部的表格
            
            DataTable table = tableCollection[0];//由於咱們只往dataset裏面放置了一張表格,因此這裏取得索引爲0的表格就是咱們剛剛查詢到的表格

            //取得表格中的數據
            //取得table中全部的行
            DataRowCollection rowCollection = table.Rows;//返回了一個行的集合

            //遍歷行的集合,取得每個行的datarow對象
            foreach (DataRow row in rowCollection)
            {
                //取得row中前8列的數據 索引0-7
                for (int i = 0; i < 8; i++)
                {
                    Console.Write(row[i]+" ");
                }
                Console.WriteLine();
                
            }
            Console.ReadKey();
        }
    }
}

查詢結果:htm

相關文章
相關標籤/搜索