User Id :    Password :      New Member   Forgot Password  
 
How to export listview in excel in asp.net
Description This article will show you how to export list view in excel sheet in asp.net.   No. of Views     11993
  Rating     4
Author Lovleen Rayat   Posted On     28 Sep 2010
Tags ASP.NET,ADO.NET,Grid and Data Source    

Sample Code   Download Code

Introduction

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");



 

About Author

About Author I am working in a private company for the last 15 months on asp.net technologies. Lovleen
No Photo
 
Country N/A
Company Indus InfoTech
Home Page N/A

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

 
 
Posted By Good one on 22 Oct 2010 at 10:20 AM
 
Good one keep writing
 
 
   
Write your comment here.
Comment
Verification Code