Tuesday, February 15, 2011

How to export data to Excel/CSV file in ASP.NET

How to export data to Excel/CSV file in ASP.NET 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("content-disposition""attachment;filename=Attendees.csv");
            Response.Charset = "";
            Response.Write("Header\r\nContentetc.");
            Response.End();
        }

How to solve problem "GridView must be placed inside a form tag with runat=server"

This one happens when try to export gridview to an Excel file.
Direct solution: Override VerifyRenderingInServerForm
Add following code to your page

public override void VerifyRenderingInServerForm(Control control)
{
return;
}

Another solution is:
Use a blank page for the exporting

How to convert Generic list into CSV format?

How to convert Generic list into CSV format?
        public static string ListToCSV<T>(List<T> list)
        {
            string output = null;

            foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
            {
                output += ((output==null)?"": ",")+ info.Name;
            }
            output += "\r\n";
            foreach (T t in list)
            {
                string oneline = null;
                foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
                {
                    oneline +=  ((info.GetValue(t, null)==null)?"": info.GetValue(t, null)) +   ",";
                }
                output += oneline + "\r\n";
            }
            return output;
        }

How to convert generic list (List) into datatable

How to convert generic list (List<t>) into datatable
        public static System.Data.DataTable ListToDataTable<T>(List<T> list)
        {
            DataTable table = new DataTable();
 
            foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
            {
                table.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            foreach (T t in list)
            {
                DataRow row = table.NewRow();
                foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null);
                }
                table.Rows.Add(row);
            }
            return table;
        }