在asp.net中匯入Excel資料到gridiew中

來源:互聯網
上載者:User

 

Code
protected void Button1_Click(object sender, EventArgs e)
{
    if (myFile.PostedFile.FileName != "")
    {
        //上傳檔案的絕對路徑
        string sFile = myFile.PostedFile.FileName;
        //擷取檔案全名
        sFile = sFile.Substring(sFile.LastIndexOf("\\") + 1);
        //擷取尾碼名
        sFile = sFile.Substring(sFile.LastIndexOf("."));
        if (sFile.ToLower() != ".xls")
        {
            Response.Write("請選擇Excel檔案!");
            Response.End();
        }
        //為了防止重名,獲得日期為檔案名稱年月日時分秒毫秒
        string datatime = System.DateTime.Now.ToString("yyyMMddHHmmssffff");
        //上傳後檔案的新名
        sFile = datatime + sFile;
        //AppDomain.CurrentDomain.BaseDirectory.ToString() 擷取此項目的根目錄
        //上傳檔案
        myFile.SaveAs(Server.MapPath(".") + "\\" + sFile);
        DataSet ds = GetExcelContent(Server.MapPath(".") + "\\" + sFile);
        this.myGridView.DataSource = ds;
        this.myGridView.DataBind();
    }
}
//讀取EXCEL到DATASET代碼:
public DataSet GetExcelContent(string filepath)
{
    string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
    OleDbConnection myConn = new OleDbConnection(strCon);
    string strCom = "SELECT * FROM [Sheet1$]";
    myConn.Open();
    OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
    //建立一個DataSet對象   
    DataSet myDataSet = new DataSet();
    //得到自己的DataSet對象   
    myCommand.Fill(myDataSet);
    //關閉此資料連結   
    myConn.Close();
    return myDataSet;
}

 

這樣就把資料匯入到DataSet中了

從DataSet中將資料匯入到庫裡貌似就好操作了

聯繫我們

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