ASP.NET Excel資料匯入資料庫

來源:互聯網
上載者:User

標籤:

今天做了一個這樣的項目,需要把Excel的資料匯入到資料庫,雖然以前也寫過,但是忘記了,所以今天找到一個更好的,收集起來。

 

下面是代碼:

 

    protected void btnImport_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定檔案
        {
            Response.Write("<script>alert(‘請您選擇Excel檔案‘)</script> ");
            return;//當無檔案時,返回
        }
        string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension獲得檔案的副檔名
        if (IsXls != ".xls")
        {
            Response.Write("<script>alert(‘只可以選擇Excel檔案‘)</script>");
            return;//當選擇的不是Excel檔案時,返回
        }
        string filename = FileUpload1.FileName;              //擷取Execle檔案名稱  DateTime日期函數
        string savePath = Server.MapPath(("upfiles\\") + filename);//Server.MapPath 獲得虛擬伺服器相對路徑
        FileUpload1.SaveAs(savePath);                        //SaveAs 將上傳的檔案內容儲存在伺服器上
        DataSet ds = ExcelSqlConnection(savePath, filename);           //調用自訂方法
        DataRow[] dr = ds.Tables[0].Select();            //定義一個DataRow數組
        int rowsnum = ds.Tables[0].Rows.Count;
        if (rowsnum == 0)
        {
            Response.Write("<script>alert(‘Excel表為空白表,無資料!‘)</script>");   //當Excel表為空白時,對使用者進行提示
        }
        else
        {
            for (int i = 0; i < dr.Length; i++)
            {
                //前面除了你需要在建立一個“upfiles”的檔案夾外,其他的都不用管了,你只需要通過下面的方式擷取Excel的值,然後再將這些值用你的方式去插入到資料庫裡面
                string title = dr[i]["標題"].ToString();
                string linkurl = dr[i]["連結地址"].ToString();
                string categoryname = dr[i]["分類"].ToString();
                string customername = dr[i]["內容商"].ToString();
                
                //Response.Write("<script>alert(‘匯入內容:" + ex.Message + "‘)</script>");
            }
            Response.Write("<script>alert(‘Excle表匯入成功!‘);</script>");
        }

    }

    #region 串連Excel  讀取Excel資料   並返回DataSet資料集合
    /// <summary>
    /// 串連Excel  讀取Excel資料   並返回DataSet資料集合
    /// </summary>
    /// <param name="filepath">Excel伺服器路徑</param>
    /// <param name="tableName">Excel表名稱</param>
    /// <returns></returns>
    public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
    {
        string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘";
        OleDbConnection ExcelConn = new OleDbConnection(strCon);
        try
        {
            string strCom = string.Format("SELECT * FROM [Sheet1$]");
            ExcelConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
            DataSet ds = new DataSet();
            myCommand.Fill(ds, "[" + tableName + "$]");
            ExcelConn.Close();
            return ds;
        }
        catch
        {
            ExcelConn.Close();
            return null;
        }
    }
    #endregion

 

 

Excel的格式如下:

 

標題 連結地址 分類 內容商
惡搞的日本女人1  http://fegnhuang.com 寫真 鳳凰視頻
惡搞的日本女人2  http://fegnhuang.com 寫真 鳳凰視頻
惡搞的日本女人3  http://fegnhuang.com 搞笑 鳳凰視頻
惡搞的日本女人4  http://fegnhuang.com 搞笑 鳳凰視頻
惡搞的日本女人5  http://fegnhuang.com 搞笑 芒果TV
惡搞的日本女人6  http://fegnhuang.com 美女 芒果TV
惡搞的日本女人7  http://fegnhuang.com 美女 芒果TV
惡搞的日本女人8  http://fegnhuang.com 美女 芒果TV
惡搞的日本女人9  http://fegnhuang.com 時尚 新浪視頻
惡搞的日本女人10  http://fegnhuang.com 時尚 新浪視頻

 

 

 其他實現方式參考:http://blog.csdn.net/lee576/archive/2011/03/02/6217811.aspx

 

轉載於:http://www.cnblogs.com/xiaopin/archive/2011/03/31/2001199.html

ASP.NET Excel資料匯入資料庫

聯繫我們

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