[后端] 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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现