Hi Gouthamnila,
Please use the below code
attachment = "attachment; filename=" + fileName + ".xls"; //Setting the attachment name.
Response.ClearContent(); //clears all content output from the buffer stream.
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
using (HtmlForm frm = new HtmlForm())
{
this.pnl1.Parent.Controls.Add(frm);
frm.Controls.Add(this.pnl1);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
}
If u want to move css style sheet to the excel Please use this code
public void ExportPanelToExcel(Panel pnl, string fileName)
{
try
{
string attachment = "attachment; filename=" + fileName + ".xls"; //Setting the attachment name.
HttpContext.Current.Response.ClearContent(); //clears all content output from the buffer stream.
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
using (HtmlForm frm = new HtmlForm())
{
pnl.Parent.Controls.Add(frm);
frm.Controls.Add(pnl);
frm.RenderControl(htw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(Constants.Constants.Contstant_CssPath));
string s = sr.ReadToEnd();
HttpContext.Current.Response.Write("<HEAD><STYLE>");
HttpContext.Current.Response.Write(s.ToString());
HttpContext.Current.Response.Write("</STYLE></HEAD>");
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
For writing to an Excel file on stream since this will give you the following message when you open the excel file.
It will prompt an error message click on yes.it will open the excel.
Some clients will not accept this solution.Please find the attached document best way do it.
Regards,
Bhanu
Download source fileRegards,
Bhanu Prakash Bysani
Gouthamnila, if this helps please login to Mark As Answer. | Alert Moderator