[后端] Asp.Net Core 导出Excel文件
Controller :
1 [HttpGet] 2 public IActionResult ExportExcel() 3 { 4 try 5 { 6 7 StringBuilder htmlcontent = new StringBuilder(); 8 9 htmlcontent.Append("<TABLE>"); 10 htmlcontent.Append("<TR>"); 11 htmlcontent.Append("<TD><B>A</B></TD>"); //列名A 12 htmlcontent.Append("<TD><B>B</B></TD>"); //列名B 13 htmlcontent.Append("<TD><B>C</B></TD>"); //列名C 14 htmlcontent.Append("<TD><B>D</B></TD>"); //列名D 15 htmlcontent.Append("<TD><B>E</B></TD>"); //列名E 16 htmlcontent.Append("</TR>"); 17 18 19 htmlcontent.Append("<TR>"); 20 htmlcontent.Append($"<TD>Value</TD>"); //列名A对应的值 21 htmlcontent.Append($"<TD>Value</TD>"); //列名B对应的值 22 htmlcontent.Append($"<TD>Value</TD>"); //列名C对应的值 23 htmlcontent.Append($"<TD>Value</TD>"); //列名D对应的值 24 htmlcontent.Append($"<TD>Value</TD>"); //列名E对应的值 25 htmlcontent.Append("</TR>"); 26 27 htmlcontent.Append("</TABLE>"); 28 29 string fileName = "文件名"; 30 31 Response.Clear(); 32 Response.Headers.Add("content-disposition", "attachment;" + "filename=" + fileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); 33 Response.ContentType = "application/vnd.ms-excel"; 34 Response.WriteAsync(htmlcontent.ToString()); 35 36 return Json(new { status = true, msg = "success" }); 37 } 38 catch (Exception ex) 39 { 40 return Json(new { status = false, msg = ex.Message }); 41 } 42 }
Js :
1 function ExportExcel() { 2 3 let _url = getCurrentURL() + `/ControllerName/ExportExcel`; 4 5 window.location.href = _url; 6 } 7 8 9 function getCurrentURL() { 10 11 var urlorigin = window.location.origin; 12 var pathname = window.location.pathname; 13 14 var lastindex = pathname.lastIndexOf(pathName); 15 16 var url = urlorigin + pathname.substring(0, lastindex); 17 url = url.trimEnd("/"); 18 if (url.substring(url.length - 1) === "/") { 19 url = url.substring(0, url.length - 1); 20 } 21 return url; 22 }