ado.net連接excel的心得

先準備一份excel取名叫Book1.xls

把Northwind的OrderID整個copy來做測試

先把他貼在excel的sheet1裡就開始玩吧

先準備一份excel取名叫Book1.xls

把Northwind的OrderID整個copy來做測試

先把他貼在excel的sheet1裡就開始玩吧

 

string strConn = string.Format(
                    @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
                    Extended Properties="Excel 8.0;HDR=yes;IMEX=1"",
                    Server.MapPath("~/Book1.xls"));
using (OleDbConnection conn = new OleDbConnection(strConn)) {
    conn.Open();
    if (conn.State == ConnectionState.Open) {
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$] WHERE EmployeeID = 5", conn);
        OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
        gridView.DataSource = reader;
        gridView.DataBind();
    }
}

沒啥了不起的,其實不過就是換個provider改用OLEDB跟連線字串要下對就好了

更新的話也一樣

給好update的command直接下command.ExecuteNonQuery()就可以更新了,不過要注意IMEX要設定好

0 is Export mode
1 is Import mode
2 is Linked mode (full update capabilities)

另外要注意的是excel沒有索引鍵所以不能用OleDbCommandBuilder配合OleDbDataAdapter來做update等修改的動作(這邊我還卡了一陣子有)

 

參考資料(保哥的寫的很詳細)

Connection strings for Excel

透過 OleDb 精準讀入 Excel 檔的方法