Thursday, March 11, 2010

Export To Excel in ASP.Net 2.0 From a GridView

/* Export To Excel From GridView*/
protected void Lnk_Click(object sender, EventArgs e)


{

try

{

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

Response.Charset = "";

//Response.Cache.SetCacheability(HttpCacheability.NoCache); //Purpose:Not Allowed to Open a File Without Saving It

Response.ContentType = "application/vnd.xls";

StringWriter stringWrite = new StringWriter();

HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

String strstyle = "";



stringWrite.GetStringBuilder().Append("<>" + "<>" + "<>" + " <>" + " <>" + "<>" + " <>" + " <>" + "<>" + " <>"); stringWrite.WriteLine(strstyle); Grid.Columns[0].Visible = false; Grid.RenderControl(htmlWrite); stringWrite.GetStringBuilder().Append("
" +

"SMS Report" +

"
" +

"
" +

"Run Date: " + DateTime.Now.Date.ToString("d") + "" +

"
");



Response.Write(stringWrite.ToString());

Response.End();

}

catch (Exception ex)

{



throw ex;

}

}

public override void VerifyRenderingInServerForm(Control control)

{

// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

//For this we override the method



}
/*Purpose:To Convert MoblieNo into Text */
int row;
for (row = 0; row <= Grid.Rows.Count - 1; row++)
{
Grid.Rows[row].Cells[4].Attributes.Add("class", "text");
//Grid.Rows[row].Cells[5].Attributes.Add("class", "text");
}

No comments:

Post a Comment