將Excel檔案中的資料匯入GridView

來源:互聯網
上載者:User

         在Asp.net中怎樣將Excel檔案中的資料匯入到GridView中呢?下面我來為大家說說這個詳細的過程。Excel檔案就是一張資料表,當然我們可以把它看作一個資料來源了。


首先我們將這張表中的資料轉換為DataTable類型的資料來源,做一個函數來解決這個問題:

private DataTable createDataSource(string strPath)        {            stringstrCon;            strCon = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + strPath  + ";Extended Properties=Excel 8.0";            OleDbConnectioncon = new OleDbConnection(strCon);            OleDbDataAdapterda = new OleDbDataAdapter("select * from [Sheet1$]", con);            DataTabledt = new DataTable();            da.Fill(dt);            returndt;        }

只需要傳入Excel檔案的路徑即可。


      其次我們就是利用這個可以函數了。要想將用戶端的Excel檔案顯示到用戶端的GridView控制項當中,這次都是用戶端的東西,在我們的伺服器端代碼是無法做到的。所以我們必須把這個Excel檔案暫時的儲存到伺服器,我們讀取伺服器端的檔案才可以實現這樣的功能。看下面的實現代碼:

protected void Button1_Click(objectsender, EventArgs e)        {            //檢查檔案是否存在            if(FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定檔案            {                Page.ClientScript.RegisterStartupScript(Page.GetType(),"message", "<script language='javascript' defer>alert('請您選擇Excel檔案!');</script>");                return;//當無檔案時,返回            }             stringfilename = DateTime.Now.ToString("yyyymmddhhMMss") +FileUpload1.FileName;            //擷取Execle檔案名稱  DateTime日期函數            stringsavePath = Server.MapPath(("~/Doc/")+ filename);//Server.MapPath 獲得虛擬伺服器相對路徑             //如果已經存在就清空            ClearFile(Server.MapPath("~/Doc/"));             FileUpload1.SaveAs(savePath);                        //SaveAs將上傳的檔案內容儲存在伺服器上                        DataTabledt = createDataSource(savePath);            GridView1.DataSource = dt;            GridView1.DataBind();         }

 

      在上面的代碼中我們用到了一個函數ClearFile,它是用來清理檔案夾的,我們將Excel檔案暫時的儲存到伺服器端的一個檔案夾中,只能暫時的儲存,那麼東西只會越來越多,而且這些東西也是一些沒用的東西,很可能導致系統效能的下降。我們就是用這個函數來清理檔案的,下面來一睹這個函數的精妙:

private void ClearFile(stringFilePath)        {            String[]files = System.IO.Directory.GetFiles(FilePath);            if(files.Length > 5)            {                for(int i = 0; i < 5; i++)                {                    try                    {                        System.IO.File.Delete(files[i]);                    }                    catch                    {                    }                 }            }        }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.