protected void Button1_Click(object sender, EventArgs e) { List<Employee> empList = new List<Employee>(); empList.Add(new Employee(20, "Ranjith")); empList.Add(new Employee(23, "Rakesh")); empList.Add(new Employee(30, "Ram")); // take excel FileName and the Exported List Export("Ranjith", empList); } public void Export(string fileName, List<Employee> empList) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}", fileName + ".xls")); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a form to contain the List Table table = new Table(); TableRow row = new TableRow(); foreach (PropertyInfo proinfo in new Employee(1,"Name").GetType().GetProperties()) { TableHeaderCell hcell = new TableHeaderCell(); hcell.Text = proinfo.Name; row.Cells.Add(hcell); } table.Rows.Add(row); // add each of the data item to the table foreach (Employee emp in empList) { TableRow row1 = new TableRow(); TableCell cellAge = new TableCell(); cellAge.Text = "" + emp.Age; TableCell cellName = new TableCell(); cellName.Text = "" + emp.Name; row1.Cells.Add(cellAge); row1.Cells.Add(cellName); table.Rows.Add(row1); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)