ASP.NET中上傳并讀取Excel文件數(shù)據(jù)示例

字號(hào):


    如何打開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對(duì)ASPNET用戶要有讀寫的權(quán)限.