DataGrid gv = new DataGrid(); gv.ItemDataBound += new DataGridItemEventHandler(dataExportExcel_ItemDataBound); gv.DataSource = dt; gv.DataBind(); string path = Server.MapPath("~/Sheets/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { StreamWriter writer = File.AppendText(path + "GridView.xls"); gv.RenderControl(hw); StringBuilder sbResponseString = new StringBuilder(); sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns: o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\"><!--[if gte mso 9]><xml><x:excelworkbook xmlns:x="#unknown"><x:excelworksheets><x:excelworksheet><x:name>"+ worksheetName +"</x:name><x:worksheetoptions><x:panes></x:panes></x:worksheetoptions></x:excelworksheet></x:excelworksheets></x:excelworkbook></xml><![endif]--></head> <body>"); sbResponseString.Append(sw + "</body></html>"); writer.WriteLine(sbResponseString.ToString()); writer.Close(); } } } void dataExportExcel_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Header) { //Header Text Format can be done as follows e.Item.Font.Bold = true; //Adding Filter/Sorting functionality for the Excel int cellIndex = 0; while (cellIndex < e.Item.Cells.Count) { e.Item.Cells[cellIndex].Attributes.Add("x:autofilter", "all"); e.Item.Cells[cellIndex].Width = 200; e.Item.Cells[cellIndex].HorizontalAlign = HorizontalAlign.Center; cellIndex++; } } if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { int cellIndex = 0; while (cellIndex < e.Item.Cells.Count) { //Any Cell specific formatting should be done here e.Item.Cells[cellIndex].HorizontalAlign = HorizontalAlign.Left; cellIndex++; } } } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)