xls表格匯入資料庫功能執行個體代碼_實用技巧

來源:互聯網
上載者:User

複製代碼 代碼如下:

protected void Button1_Click(object sender, EventArgs e)
        {

            if (FileUpload1.HasFile == false)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "shifou", "<script>alert('請您選擇   Excel檔案')</script> ");
                return;
            }
            string Name = FileUpload1.PostedFile.FileName; //擷取初始檔案名稱
            int j = Name.LastIndexOf("."); //取得檔案名稱中最後一個"."的索引
            string newext1 = Name.Substring(j); //擷取副檔名
            if (newext1 != ".xls" && newext1 != ".xlsx")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "wenjian", "<script>alert('只可以選擇  Excel檔案')</script>");
                return;//當選擇的不是Excel檔案時,返回
            }
            SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
            cn.Open();
            //savePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);//    FileUpload1.PostedFile.FileName.ToString();
            if (FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定檔案
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "wenjian", "<script>alert('Excel路徑有  問題')</script>");
                return;//當無檔案時,返回
            }

            filename = FileUpload1.FileName;  //Path.GetFileNameWithoutExtension  (FileUpload1.PostedFile.FileName);
            savePath = Server.MapPath(("../../UploadFiles/xls/") + filename);
            FileUpload1.SaveAs(savePath); //儲存XLS檔案

            DataSet ds = ExecleDs(savePath, filename);          //調用自訂方法
            DataRow[] dr = ds.Tables[0].Select();            //定義一個DataRow數組
            int rowsnum = ds.Tables[0].Rows.Count;
            if (rowsnum == 0)
            {
                //當Excel表為空白時,對使用者進行提示
                Page.ClientScript.RegisterStartupScript(this.GetType(), "kong", "<script>alert('Excel表為空白表,   無資料!')</script>");
            }
            else
            {
                    for (int i = 0; i < dr.Length; i++)
                    {

        //自訂的model-student
                        student.belong = "";
                        student.birthday = Convert.ToDateTime("1990-1-1");
                        student.classid = 1;
                        student.id = 1;
                        student.inschool = Convert.ToDateTime("1990-1-1");
                        student.phone = "";
                        student.sex = "";
                        student.type = "";
                        student.isaudite = "否";
                        student.roleid = Convert.ToInt32("22");
                        try
                        {
                            student.stuname = dr[i]["姓名"].ToString();
                            student.stuid = dr[i]["學號"].ToString();
                            student.username = dr[i]["姓名"].ToString();
                            student.userpassword = dr[i]["學號"].ToString();
                        }
                        catch(Exception ex) {
                            Response.Write("<script>alert('"+ex.Message+"')</script>");
                            return;
                        }
                        DataSet ds2 = studentbll.GetList("stuid='" + dr[i]["學號"].ToString() + "'");
                        if (ds2.Tables[0].Rows.Count == 0)
                        {
                            try
                            {
                                bool addstudent = Convert.ToBoolean(studentbll.Add(student));
                                if (addstudent)
    Page.ClientScript.RegisterStartupScript(this.GetType(), "daochu",     "<script>alert('Excle表匯入成功!')</script>");
                            }
                            catch (MembershipCreateUserException ex)       //捕捉異常
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "chongfu",      "<script>alert('匯入內容:" + ex.Message + "')</script> ");
                            }
                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "chongfu", "<script>alert    ('內容重複!禁止匯入')</script> ");
                            continue;
                        }
                    }
            }
        }

  public DataSet ExecleDs(string filenameurl, string table)
        {
            string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + filenameurl + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";//這段字串注意空格別寫錯否則會報錯
            OleDbConnection conn = new OleDbConnection(strConn);
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet18$]", conn);//【sheet18$】是表格名

            DataSet ds = new DataSet();
            odda.Fill(ds, table);
            return ds;
        }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.