Skip to content

Exports gridview and prints it in excel

djamel zahal

Asked Mar 1, 2012, 5:53 AM EST1 answer
Share
LinkedInX
I'm exporting a gridView into excel file.  


it is exported well but the problem is that i have 30 pages when i want to print instead of 19 pages.  


i debugged and in my content, i dont see blanc or br at the end..this problem is visible only for printing.  


thank you for help.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Code
    try this one, though I didn't test this on printing the exported XLS
    protected void ExportToXls_Click(object sender, EventArgs e) //On click Event of a control (button/link button/hyperlink)
     {
            this.DataGridView1.AllowPaging = false;
            ExportGridViewToExcel(Response, this.DataGridView1, "Exported.xls");
     }
     public void ExportGridViewToExcel(HttpResponse response, GridView gvControl, string fileName)
            {
                string attachment = "";
                System.IO.StringWriter sw = new System.IO.StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                response.ClearContent();
                response.AddHeader("content-disposition", attachment);
                gvControl.AllowPaging = false;
                gvControl.DataBind();
                gvControl.RenderControl(htw);
                response.Write(sw.ToString());
                response.Flush();
                response.End();
                gvControl.AllowPaging = true;
            }
     public override void VerifyRenderingInServerForm(Control control) // I just got this in forum just
               // add this. I don't why but it will work if this is added
            {
            }
    0