Following function exports your GridView data to Excel. It has full support for unicode characters.
///
/// Grid to Excel with
Custom FileName.
///
///
///
///
public static void GridToExcel(HttpResponse
response, System.Web.UI.WebControls.GridView
gv, string filename)
{
response.Clear();
ContentDisposition cd = new
ContentDisposition
{
Inline = false,
FileName = filename + "_" + DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_").Replace("-", "_")
+ ".xls"
};
response.AddHeader("content-disposition",
cd.ToString());
// If you want the option to open the Excel file without
saving than
// comment out the line below
//
Response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "application/ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter
htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.HtmlControls.HtmlForm
hform = new System.Web.UI.HtmlControls.HtmlForm();
gv.Parent.Controls.Add(hform);
hform.Attributes["runat"] =
"server";
hform.Controls.Add(gv);
hform.RenderControl(htmlWrite);
response.Write("");
response.Write("
"
+ filename + "
");
response.Write("
Date : "
+ DateTime.Now.ToLongDateString()
+ "
");
response.Write(stringWrite.ToString());
response.End();
}
///
/// Grid to Excel with
Custom FileName and Custom Header.
///
///
///
///
///
public static void GridToExcel(HttpResponse
response, System.Web.UI.WebControls.GridView
gv, string filename, string
header)
{
response.Clear();
ContentDisposition cd = new
ContentDisposition
{
Inline = false,
FileName = filename + "_" +
DateTime.Now.ToString().Replace(" ", "_").Replace("/", "_").Replace(":", "_").Replace("-", "_")
+ ".xls"
};
response.Charset = "UTF-8";
response.AddHeader("content-disposition",
cd.ToString());
// If you want the option to open the Excel file without
saving than
// comment out the line below
//
Response.Cache.SetCacheability(HttpCacheability.NoCache);
response.ContentType = "application/ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter
htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.HtmlControls.HtmlForm
hform = new System.Web.UI.HtmlControls.HtmlForm();
gv.Parent.Controls.Add(hform);
hform.Attributes["runat"] =
"server";
hform.Controls.Add(gv);
hform.RenderControl(htmlWrite);
response.Write("");
response.Write("
"
+ header + "
");
response.Write("
Date : "
+ DateTime.Now.ToLongDateString()
+ "
");
response.Write(stringWrite.ToString());
response.End();
}