GridView读取Excel数据

private DataSet CreateDataSource()
    {
        string strCon;
        strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.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_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();

   }

如果GridView存在模板列,其中包含子控件,例如CheckBox等,导出EXCEL后就会出现该区域的不规律。所以要对模板列单独处理(转载)

 


public static void PrepareGridViewForExport(Control gv)//模式化特殊元素 flashcong
    {

        LinkButton lb = new LinkButton();
        Literal l = new Literal();
        string name = String.Empty;

        for (int i = 0; i < gv.Controls.Count; i++)
        {

            if (gv.Controls[i].GetType() == typeof(LinkButton))
            {

                l.Text = (gv.Controls[i] as LinkButton).Text;
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(DropDownList))
            {

                l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(CheckBox))
            {

               l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
               gv.Controls.Remove(gv.Controls[i]);
               gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(ImageButton))
            {
              l.Text = "图片";
              gv.Controls.Remove(gv.Controls[i]);
              gv.Controls.AddAt(i, l);
            }

            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }

        }

    }

你可能感兴趣的:(GridView)