下载excel在webform以及winform之间的区别还真是不少,之前我在9you做多了winform,会用到interop来下载word和excel,甚至在webbrower控件上显示这些信息,到了2010以后openxml大行其道后,我们越来越熟悉用openxml来扣ExcelWorksheet来得到里面的内容,再通过LoadFromDataTable来填充到我们的excel,更有摄甚着,可以用parellal的task来做异步并行来提高导出多个表到工作簿,但是这些一旦用来在web则完全不是那会事情了,因为下载的excel永远在服务器本地,我们需要公布其服务器的地址来给客户下载。之前在东方财富用了这个方法,但是没有领导这个简单的流操作才是避开权限的关键。不用去用a标签的type为file来指定下载地址,这样可以由客户端自己决定保存到哪里。我这里有两种方法来实现下载,NPOI和Myxls,NPO用在mvc上比较好用,而Myxls用在webform的Page上比较好用。
/// <summary>
/// NPOI插件保存excel到网页,用于MVC4
/// </summary>
/// <returns></returns>
public ActionResult DownLoadExcel()
{
string Path = AppDomain.CurrentDomain.BaseDirectory + "Resource\\Config\\DatetimeConfig.xml";
XElement xele = XElement.Load(Path);
if ((string)xele.Attribute("content") != "")
{
DateTime dateTime = DateTime.Parse((string) xele.Attribute("content"));
TimeSpan span = DateTime.Now - dateTime;
if (span.TotalMinutes < 1)
{
return new EmptyResult();
}
}
//延迟30分钟再可以提交
string sql = "SELECT [UserID],[UserCode],[UserName],[ParentID],[Position],[Mobile],[Email],[Levels],[AttentionTime]FROM Users WHERE CreateStatus = 1 AND(AttentionState = 1);