asp.net:上傳excel表格到SQL Server數據庫

1. 在web設計頁面中,設計成如下的界面(包括2個label,1個fileupload,1個dropdownlist,2個按鈕)。首先點擊“瀏覽”,選擇要上傳的excel表格路徑,然後點擊“查看數據”,在dropdownlist中顯示excel中的所有表名,選擇要上傳的表明,點擊“導入”,則可將選定表的數據導入到數據庫中。

image

2. 具體代碼: 

static string path;//定義路徑
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    //導入選定的excel指定的工作表
    protected void Button1_Click(object sender, EventArgs e)
    {
        //確定導入的總的工程數量
        int countContract = 0;

        if (path == "")//如果路徑爲空
        {
            Response.Write("");
        }
        else//路徑不爲空
        {
            try
            {
                string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + path + "';Extended Properties=Excel 8.0";
                OleDbConnection cnnxls = new OleDbConnection(mystring);
                OleDbDataAdapter myDa = new OleDbDataAdapter("select * from ["+DropDownList1 .SelectedItem.Text .ToString ().Trim ()+"]", cnnxls);
                DataSet myDs = new DataSet();
                myDa.Fill(myDs);
                //excel中有記錄的話
                if (myDs.Tables[0].Rows.Count > 0)
                {
                    string strSql = "";
                    string CnnString = "Provider=SQLOLEDB;database=brcm;server=(local);uid=sa;pwd=sa";
                    OleDbConnection conn = new OleDbConnection(CnnString);
                    conn.Open();
                    OleDbCommand myCmd = null;

                    #region//導入excel中的每行
                    for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
                    {
                        //判斷excel第一列是否爲空,爲空,則不導入。
                        object a = myDs.Tables[0].Rows[i].ItemArray[0].ToString();
                        if (myDs.Tables[0].Rows[i].ItemArray[0].ToString() == "" || myDs.Tables[0].Rows[i].ItemArray[0].ToString() == "序號")
                        {
                            ;
                        }
                        //第一列不爲空
                        else
                        {   //判斷是否有重複項目
                            string conn1 = "Data Source=(local);Database=brcm;User ID=sa;Password=sa";
                            SqlConnection thisConnection = new SqlConnection(conn1);
                            thisConnection.Open();
                            string isExistString = "SELECT * FROM ContractList WHERE Contract_Number='" + myDs.Tables[0].Rows[i].ItemArray[3].ToString() + "'";
                            SqlCommand testExistCommand = new SqlCommand(isExistString, thisConnection);
                            SqlDataAdapter thisAdapter = new SqlDataAdapter(isExistString, thisConnection);
                            DataSet thisDataSet = new DataSet();
                            thisAdapter.Fill(thisDataSet, "ContractList");
                            DataRowCollection rows = thisDataSet.Tables["ContractList"].Rows;

                            if (rows.Count == 0)//不存在,則導入
                            {

                                strSql = "insert into ContractList(Simple_Number,Contract_Number,Contract_Type,Contract_Date,Project_Manager,Customer_Company,Contract_Name,Contract_Amount,Fu_Number) values ('";
                                strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + "', '";//序號,簡易編號
                                strSql += myDs.Tables[0].Rows[i].ItemArray[3].ToString() + "', '";//合同編號
                                strSql += myDs.Tables[0].Rows[i].ItemArray[7].ToString() + "', '";//合同類型
                                strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "', '";//簽約日期
                                strSql += myDs.Tables[0].Rows[i].ItemArray[2].ToString() + "', '";//負責人
                                strSql += myDs.Tables[0].Rows[i].ItemArray[4].ToString() + "', '";//需方單位名稱
                                strSql += myDs.Tables[0].Rows[i].ItemArray[5].ToString() + "', '";//安裝地點
                                strSql += myDs.Tables[0].Rows[i].ItemArray[6].ToString() + "', '";//合同總金額
                                strSql += myDs.Tables[0].Rows[i].ItemArray[8].ToString() + "')";//附號
                                countContract++;
                                myCmd = new OleDbCommand(strSql, conn);
                                myCmd.ExecuteNonQuery();
                            }
                            else//存在,提示有重複項目,不導入。
                            {
                                Response.Write("");
                            }
                            thisAdapter.Dispose();
                            thisConnection.Close();

                        }
                    }
                    conn.Close();
                    Response.Write("");
                    #endregion
                }
            }
            catch
            {
                Response.Write("");
            }
        }
    }

    //查看數據
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.FileUpload1.HasFile)
            {
                //清空
                DropDownList1.Items.Clear();
                DataTable inputdt = new DataTable();
                int len = this.FileUpload1.FileName.ToString().Trim().Length;
                path = "~/temp/upfile/" + this.FileUpload1.FileName.ToString().Trim();
                path = Server.MapPath(path);
                this.FileUpload1.SaveAs(path); //上傳文件

                //讀取所有excel工作,並添加到dropdownlist中
                OleDbConnection oleConn = new OleDbConnection();
                oleConn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0;data source='"+path+"';Extended Properties=Excel 8.0;";
                oleConn.Open();
                DataTable dtOle = oleConn.GetSchema("Tables");
                DataTableReader dtReader = new DataTableReader(dtOle);
                DropDownList1 .Items .Add (new ListItem ("-=請選擇=-","0"));
                for (int i = 0; i < dtOle.Rows.Count;i++ )
                {
                    DropDownList1.Items.Add(new ListItem(dtOle.Rows[i]["TABLE_NAME"].ToString(), (i+1).ToString ()));
                }

                dtOle = null;
                oleConn.Close();
            }
            else
                throw new Exception("請選擇導入表的路徑");
        }
        catch (Exception ex)
        {
            Response.Write("");
        }

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章