0

I used this code for exploring grid to excel.I got this code from net.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

When I am using this code,grid data get display in excel,but that does not have vertical and horizontal lines.It shows gridview column name as link not normal text.I have not used any theme to gridview and columns are autogenerated.One column say col3 contain more description so it's data get displayed at top when second row start,still it's discription shown in cell2.So I wanted to add vertical and horizontal lines,in that.So it is easy to come to know which data of belong to which id.I want to format col 1 also which is of number format only and decimal places zero.

 1 col1    col2              col3
                                     hjhhjhjhjhjhjhjhjhjhjbbv
                                     gfgfgfuiuiuiuiui
    2 9.12E+11   gkjj                etwtrtrwqtrtttwwtretqwfe
                                     dear member
                                      gffgf

    3 565E+11 hghgh
Jui Test
  • 2,399
  • 14
  • 49
  • 76
  • But that's not a real Excel file - you're feeding Excel HTML with an Excel content-type. You'll get away with this with real Excel but won't work for e.g. the free Excel viewer. You should use [one of these libraries](http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c-sharp) to generate a real Excel file. Then you'll be able to control the cell formats, etc. – Rup Nov 14 '11 at 10:36

1 Answers1

0

Bind grid data on page load event and then try to export again.. follow this link's code.. may be it will be good rather than others...

Exporting GridView Data to Excel

Code Snippet:

private void ExportGridView()
    {
        string attachment = "attachment; filename=Contacts.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

Note: There are some comments also posted which also have some information..

To Format GridView according to grid controls when you are exporting data to excel then follow the below link: ASP.Net 2.0: Export GridView to Excel

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75