MVC 导出Execl 的总结几种方式 (二)
2024-10-20 07:46:42
接着上面的来,继续导出Execl 的功能
使用FileResult 方式直接可以生产Execl ,这样我们将会写大量处理后台的代码,个人感觉不好,只是展示出来,提供参考
第一步:编辑控制器
public FileResult ExportFile()
{
var list = GetList(); var sbHtml = new StringBuilder();
string title = "order";
//标题
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
sbHtml.Append("<tr>");
sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center; font-weight:bold;' height='30' colspan='3'>{0}</td>", title);
sbHtml.Append("</tr>");
sbHtml.Append("</table>");
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0' style='font-size: 12px;'>");
var lstTitle = new List<string> { "Year", "Week", "Date" }; //编写表头
sbHtml.Append("<tr>");
foreach (var item in lstTitle)
{
sbHtml.AppendFormat("<td style='text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
sbHtml.Append("</tr>");
int i = ; var strDataType = string.Empty;
var strQuestion = string.Empty; foreach (var item in list)
{ sbHtml.Append("</tr>");
sbHtml.AppendFormat("<td align='center'>{0}</td><td align='center'>{1}</td><td align='center'>{2}</td>", item.Id, item.Name,item.CreateTime.ToString("yyyy-MM-dd hh:mm:ss") );
sbHtml.Append("</tr>");
i++; }
sbHtml.Append("</table>"); byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString()); string fileName = title + ".xls"; if (Request.Browser.Browser == "IE")
{
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", HttpUtility.UrlEncode(fileName, Encoding.UTF8)));
}
return File(fileContents, "application/ms-excel", fileName);
}
第二步:前端调用
function ExportFile() { window.open("/Home/ExportFile"); }
OK ,这样就好 控制器里面的代码也是挺简单,自己看看吧
最新文章
- Bootstrap<;基础十七>;导航栏
- D3树状图异步按需加载数据
- block使用小结、在arc中使用block、如何防止循环引用
- xcode Git
- Linux init进程详解
- javascript防止SQL注入
- 如何实现一个c/s模式的flv视频点播系统
- leetcode problem 41 -- First Missing Positive
- DSPack各种使用方法
- nginx 编译选项
- (转).NET平台开源JSON库LitJSON的使用方法
- (转)Javascript 面向对象编程(一):封装(作者:阮一峰)
- elasticsearch-head的安装
- vue 之 .sync 修饰符
- 5.06-re
- MinFilter(MaxFilter)快速算法C++实现
- IDEA复制某个类的包名路径
- 物联网架构成长之路(10)-Nginx负载均衡
- 使用maven构建一个web项目
- c#FTP应用---FileZilla Server