/////////////////.cshtml
<button id="btnExport" onclick="DownloadExcel()" class="btn
btn-danger pull-right" title="Download
Excel"> Export </button>
//////////////// Js
<script type="text/javascript">
function DownloadExcel() {
var urls = "@Url.Action("MethodName", "ControllerName")"+"?FileNames=test";
window.location = urls;}
</script>
///////////////////// Controller
public ActionResult Download_Clinic_Details(string FileNames)
{
DataTable dt = new DataTable();
dt.Columns.Add("RollNo");
dt.Columns.Add("Name");
dt.Columns.Add("College Name");
DataRow dr;
int rn = 1001;
for (int i = 0; i
< 10; i++)
{
dr = dt.NewRow();
dr[0] = (rn).ToString();
dr[1] = "Raja_" + i.ToString();
dr[2] = "Name of IT College_" +
i.ToString();
dt.Rows.Add(dr);
rn++;
}
dt.AcceptChanges();
StringBuilder StrExport = new StringBuilder();
StrExport.Append(@"<html xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:w='urn:schemas-microsoft-com:office:excel'
xmlns='http://www.w3.org/TR/REC-html40'><head><title>Time</title>");
StrExport.Append(@"<body lang=EN-US style='mso-element:header'
id=h1><span style='mso--code:DATE'></span><div
class=Section1>");
StrExport.Append("<div style='font-size:12px;'>");
//
StrExport.Append(dvInfo.InnerHtml);
StrExport.Append("<div><center style='font-size:
12pt;'><b>This excel generated by Krishna kumar chaturvedi</b></center></div><br
/>");
StrExport.Append("<table align='center' border='1' bordercolor='#00aeef'
class='reporttable1' cellspacing='0' cellpadding='0' style='font-size:
10pt;'>");
//StrExport.Append("<tr
align='center'>");
string[] sty = { "70", "300", "90" };
for (int i = 0; i
< dt.Columns.Count; i++)
{
StrExport.Append("<th style='width: " + sty[i]
+ "px;word-break: break-word;'>" + dt.Columns[i].ColumnName + "</th>");
}
StrExport.Append("</tr>");
for (int i = 0; i
< dt.Rows.Count; i++)
{
StrExport.Append("<tr>");
for (int c = 0; c
< dt.Columns.Count; c++)
{
StrExport.Append("<td>" +
Convert.ToString(dt.Rows[i][c]) + "</td>");
}
StrExport.Append("</tr>");
}
StrExport.Append("</table>");
StrExport.Append("</div></body></html>");
FileNames = FileNames+""+System.DateTime.Now.ToString("yyyyMMddhhmmss");
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" +
FileNames+".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] buffer =
System.Text.Encoding.UTF8.GetBytes(StrExport.ToString());
return File(buffer, "application/vnd.ms-excel");
}
No comments:
Post a Comment