Monday, September 21, 2009

Exporting specific columns in a grid to Excel in ASP.NET

Here is the code for exporting only specific columns in a grid to Excel in ASP.NET


HtmlForm form = new HtmlForm();
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
GridView grid = new GridView();
List<Test> t = (List<Test>)GridView1.DataSource;
DataTable dt = Common.ToDataTable<Test>(t);
dt.Columns.Remove("ColB");
grid.DataSource = dt;
grid.DataBind();
form.Controls.Add(grid);
this.Controls.Add(form);
form.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();

public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }

No comments:

Post a Comment