asp.net中上傳并讀取excel文件數(shù)據(jù)示例

字號:


    如何打開excel數(shù)據(jù)庫文件,想必有很多朋友都不清楚吧,下面通過一個(gè)簡單的例子,實(shí)現(xiàn)讀取excel數(shù)據(jù)文件
    在csdn中,經(jīng)常有人問如何打開excel數(shù)據(jù)庫文件。本文通過一個(gè)簡單的例子,實(shí)現(xiàn)讀取excel數(shù)據(jù)文件。
    首先,創(chuàng)建一個(gè)web應(yīng)用程序項(xiàng)目,在web頁中添加一個(gè)datagrid控件、一個(gè)文件控件和一個(gè)按鈕控件。
    代碼如下:
    <input id=file1 type=file name=file1 runat=server>
    <asp:button id=button1 runat=server text=button></asp:button>
    <asp:datagrid id=datagrid1 runat=server></asp:datagrid>
    在代碼視圖中首先導(dǎo)入oledb命名空間:
    using system.data.oledb;
    在按鈕的單擊事件中輸入如下代碼:
    代碼如下:
    string strpath=c://test// + datetime.now.tostring(yyyymmddhhmmss) + .xls;
    file1.postedfile.saveas(strpath);
    string mystring=provider = microsoft.jet.oledb.4.0 ; data source = '+ strpath +';extended properties=excel 8.0;
    oledbconnection cnnxls = new oledbconnection (mystring);
    oledbdataadapter myda =new oledbdataadapter(select * from [sheet1$],cnnxls);
    dataset myds =new dataset();
    myda.fill(myds);
    datagrid1.datasource=myds.tables[0];
    datagrid1.databind();
    其中c:/test對aspnet用戶要有讀寫的權(quán)限.