Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

Can anyone tell me how to generate a new excel 2007 file from a dataset directly.
I have used a piece of code, but it its generating the excel file in old 2003 format.

My Code is:
C#
public void ExportDataSetToExcel(DataSet ds, string filename)
{
    HttpResponse response = HttpContext.Current.Response;

    response.Clear();
    response.Charset = "";

    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    // instantiate a datagrid
    DataGrid dg = new DataGrid();
    dg.DataSource = ds.Tables[0];

    dg.DataBind();
    dg.RenderControl(htw);
    response.Write(sw.ToString());
    response.End();
}

Thanks in advance...
Posted
Updated 9-Feb-12 0:32am
v2
Comments
André Kraak 9-Feb-12 6:33am    
Edited question:
Added pre tags

hi dude,

For this you need to install 2007 Microsoft Tool then this will code will convert the data set into excel


In your page directive put EnableEventValidation=false

C#
public void ExportGridExel()
            {
                  string attachment = "attachment; filename=EstablishmentAllotmentDetail.xls";
                  Response.ClearContent();
                  Response.AddHeader("content-disposition", attachment);
                  Response.ContentType = "application/ms-excel";
                  StringWriter sw = new StringWriter();
                  HtmlTextWriter htw = new HtmlTextWriter(sw);
                  HtmlForm frm = new HtmlForm();
                  if (trAllotmentDetail.Visible == true)
                  {
                        pnlGrid.Parent.Controls.Add(frm);
                        frm.Controls.Add(pnlGrid);
                  }
                  if (trAllotmentDetailDivision.Visible == true)
                  {
                        pnlDivision.Parent.Controls.Add(frm);
                        frm.Controls.Add(pnlDivision);
                  }
                  frm.Attributes["runat"] = "server";
                  frm.RenderControl(htw);
                  Response.Write(sw.ToString());
                  Response.End();
            }

public override void VerifyRenderingInServerForm(Control control)
      {
            /* Verifies that the control is rendered */
   }
 
Share this answer
 
Comments
Venkat_C6 9-Feb-12 5:49am    
Thanks prashant...

But is there any way to get without installing 2007..?
By following the below link we can get the code of writing dataset into a excel 2007 file.

www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900