How to export listview in excel in asp.netIntroduction
We often need to export data from a listview control to excel sheet. This article will explain you how to export list view data in excel sheet in asp.net.
public void ExportIntoExcel(ListView lvExport, string Header,string FileName)
{
try
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename="+FileName+".xls");
System.Web.HttpContext.Current.Response.Charset = "";
System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter stringWrite = new StringWriter();
stringWrite.Write(Header);
stringWrite.WriteLine();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
HtmlForm frm = new HtmlForm();
lvExport.Parent.Controls.Add(frm);
frm.Controls.Add(lvExport);
frm.RenderControl(htmlWrite);
System.Web.HttpContext.Current.Response.Write(stringWrite.ToString());
}
catch (Exception ex)
{
}
finally
{
System.Web.HttpContext.Current.Response.End();
}
}
The above code is complete code for exporting a listview contains to excel.
Code Explanation
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
The code above defines the type of the file in which the listview containts will be shown. If you want to export it into word document just specify “application/vnd.ms-word” as ContentType. The listview contains will be exported to word document.
To open the file as attachment we can use following code.
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename="+FileName+".xls");