// Export to Excel public void ExportToExcel(ExportParameter.Excel parameter) { try { if (parameter == null) { throw new Exception("parameter to export is not null."); } string filename = parameter.FileName; string html = GetContentExcel(parameter); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", filename)); System.Web.HttpContext.Current.Response.Write(html); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } catch (Exception ex) { throw ex; } }
// set parameter for export to Excel public ExportParameter.Excel SetReportParameterExcel(string filename, PropertyDescriptorCollection headerExport, IEnumerable <object> BodyExport) { try { if (string.IsNullOrEmpty(filename)) { throw new Exception("Filename to export is not null or empty."); } if (headerExport == null) { throw new Exception("Data invalid."); } var parameter = new ExportParameter.Excel() { FileName = filename, HeaderExport = headerExport, BodyExport = BodyExport }; return(parameter); } catch (Exception ex) { throw ex; } }
private string GetContentExcel(ExportParameter.Excel parameter) { string html = @"<head> <meta http-equiv=Content-Type content='text/html; charset=utf-8'> <style> table .txtStyle { mso-number-format:'\@' } </style> </head> <body> <font style='font-size:10.0pt; font-family:tahoma;'> <br><br><br> <table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:tahoma; background:white;'> {@header} {@detail} </table> </font> </body>"; string headTable = string.Empty; string detailTable = string.Empty; // header headTable += "<tr>"; foreach (PropertyDescriptor header in parameter.HeaderExport) { headTable += string.Format("<td><b>{0}</b></td>", header.DisplayName); } headTable += "</tr>"; // body foreach (var item in parameter.BodyExport) { detailTable += "<tr>"; foreach (PropertyDescriptor header in parameter.HeaderExport) { var _value = header.GetValue(item) ?? DBNull.Value; detailTable += string.Format("<td class='txtStyle'>{0}</td>", MakeValueExcel(_value)); } detailTable += "</tr>"; } html = html .Replace("{@header}", headTable) .Replace("{@detail}", detailTable); return(html); }