在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 { } } } }