protected void Button1_Click(object sender, EventArgs e)
    {
        Export("application/ms-excel", "Employee information.xls");
    }
    /// <summary>
    /// 定义导出Excel的函数
    /// </summary>
    /// <param name="FileType"></param>
    /// <param name="FileName"></param>
    private void Export(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    
    public override void VerifyRenderingInServerForm(Control control)
    {
    }上述就是将所有字段进行导出,我现在只想其中的三个列 如:id、name、sex导出,其它字段如age、......等等字段不需要导出,请高手赐教啊!!!

解决方案 »

  1.   


    for (int i = 0; i < GridView1.Rows.Count; i++)
                    {
                        Label lblID = (Label)GridView1.Rows[i].Cells[0].FindControl("lblID");
                        Label lblName = (Label)GridView1.Rows[i].Cells[0].FindControl("lblName");
                        Label lblSex = (Label)GridView1.Rows[i].Cells[0].FindControl("lblSex");
                        string strID = "";
                        string strName = "";
                        string strSex = "";
                        if (lblID != null)
                        {
                            strID = lblID.Text;
                        }
                        if (lblName != null)
                        {
                            strName = lblName.Text;
                        }
                        if (lblSex != null)
                        {
                            strSex = lblSex.Text;
                        }
                    }
      

  2.   

    Cells[0]这里 你自己修改下 
      

  3.   

        public void ExportToExcel(DataTable dt,Page thispage) 
        {
            StringWriter sw = new StringWriter();//outputstream
            HtmlTextWriter hw = new HtmlTextWriter(sw);//htmlstream
            DataGrid dg = new DataGrid();
            dg.DataSource = dt.DefaultView;
            dg.DataBind();        dg.RenderControl(hw);        thispage.Response.ContentType = "application/vnd.ms-excel";//type=excel       
            thispage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            thispage.Response.Write(sw.ToString());
            thispage.Response.End();
        }
      

  4.   

    GridView1.Columns[0].Visible = false;
    GridView1.Columns[1].Visible = false;