This post was most recently updated on March 15th, 2016
1 2 3 4 5 |
protected void cmdExport_Click(object sender, EventArgs e) { // Add logic to get the data to be exported into the DataTable dtReportData GenerateExcel(dtReportData); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
public static void GenerateExcel(DataTable dtSource) { StringBuilder sbDocBody = new StringBuilder(); ; try { // Declare Styles sbDocBody.Append("<style>"); sbDocBody.Append(".Header { background-color:Navy; color:#ffffff; font-weight:bold;font-family:Verdana; font-size:12px;}"); sbDocBody.Append(".SectionHeader { background-color:#8080aa; color:#ffffff; font-family:Verdana; font-size:12px;font-weight:bold;}"); sbDocBody.Append(".Content { background-color:#ccccff; color:#000000; font-family:Verdana; font-size:12px;text-align:left}"); sbDocBody.Append(".Label { background-color:#ccccee; color:#000000; font-family:Verdana; font-size:12px; text-align:right;}"); sbDocBody.Append("</style>"); // StringBuilder sbContent = new StringBuilder(); ; sbDocBody.Append("<br><table align=\"center\" cellpadding=1 cellspacing=0 style=\"background-color:#000000;\">"); sbDocBody.Append("<tr><td width=\"500\">"); sbDocBody.Append("<table width=\"100%\" cellpadding=1 cellspacing=2 style=\"background-color:#ffffff;\">"); // if (dtSource.Rows.Count > 0) { sbDocBody.Append("<tr><td>"); sbDocBody.Append("<table width=\"600\" cellpadding=\"0\" cellspacing=\"2\"><tr><td>"); // // Add Column Headers sbDocBody.Append("<tr><td width=\"25\"> </td></tr>"); sbDocBody.Append("<tr>"); sbDocBody.Append("<td> </td>"); for (int i = 0; i < dtSource.Columns.Count; i++) { sbDocBody.Append("<td class=\"Header\" width=\"120\">" + dtSource.Columns[i].ToString().Replace(".", "<br>") + "</td>"); } sbDocBody.Append("</tr>"); // // Add Data Rows for (int i = 0; i < dtSource.Rows.Count; i++) { sbDocBody.Append("<tr>"); sbDocBody.Append("<td> </td>"); for (int j = 0; j < dtSource.Columns.Count; j++) { sbDocBody.Append("<td class=\"Content\">" + dtSource.Rows[i][j].ToString() + "</td>"); } sbDocBody.Append("</tr>"); } sbDocBody.Append("</table>"); sbDocBody.Append("</td></tr></table>"); sbDocBody.Append("</td></tr></table>"); } // HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; // HttpContext.Current.Response.AppendHeader("Content-Type", "application/ms-excel"); HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment; filename=EmployeeDetails.xls"); HttpContext.Current.Response.Write(sbDocBody.ToString()); HttpContext.Current.Response.End(); } catch (Exception ex) { // Ignore this error as this is caused due to termination of the Response Stream. } } |