将excel 导入到gridview

private DataSet CreateDataSource()
    {
        string strCon;
        strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Book1.xls") + "; Extended Properties=Excel 8.0;";
        OleDbConnection olecon = new OleDbConnection(strCon);
        OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);
        DataSet myds = new DataSet();
        myda.Fill(myds);
        return myds;
    }

    protected void Button1_ServerClick(object sender, EventArgs e)//导入数据按钮
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();
    }

需要注意的是: excel 必须是自己把数据录进去的,不能对导出的excel进行导入,excel不能有合并行。

1.Server.MapPath("~/Book1.xls")   注意xls的文件所在。   sheet1 是xls里面的表名,打开xls 左下角.

你可能感兴趣的:(GridView)