上傳EXCLE檔案

zhaohjjq發表於2013-10-16

1.新增方法  

      /// <summary>

        /// 上傳方法
        /// </summary>
        /// <param name="myFileUpload"></param>
        /// <returns></returns>
        private bool Upload(FileUpload myFileUpload)
        {
            bool flag = false; //是否允許上載
            bool fileAllow = false; //設定允許上載的擴充套件檔名型別 
            string[] allowExtensions = { ".xls" }; //取得網站根目錄路徑 
            string path = HttpContext.Current.Request.MapPath("~/");
            if (myFileUpload.HasFile)
            {
                string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
                for (int i = 0; i < allowExtensions.Length; i++)
                {
                    if (fileExtension == allowExtensions[i])
                    { fileAllow = true; }
                }
                if (fileAllow)
                {
                    try
                    {
                        //儲存檔案到資料夾 
                     //  myFileUpload.SaveAs(path + myFileUpload.FileName);
                        myFileUpload.SaveAs(path+"k.xls");
                        Response.Write("檔案匯入成功");
                        list_Client.Items.Clear();
                        flag = true;
                    }
                    catch (Exception ex)
                    {
                    }
                }
                else
                {
                    Response.Write("不允許上載:" + myFileUpload.PostedFile.FileName + ",只能上傳xls的檔案,請檢查!");
                    flag = false;
                }
            }
            else
            {
                Response.Write("請選擇要匯入的excel檔案!");
                flag = false;
            }
            return flag;
        }

2.上傳事件 
        protected void Button4_Click(object sender, EventArgs e)
        {
            bool b = Upload(fuExcel); // 上傳excel檔案 
            Bind();

        }


/**********************************************************html***********************************************************************/

3.靜態頁面:

         <div><asp:FileUpload ID="fuExcel" runat="server" />

        <asp:Button ID="Button4" runat="server" Text="匯入資料" onclick="Button4_Click" /></div>