使用的坑

  • Post author:
  • Post category:java


这阶段在做一个文件输出浏览器保存的内容,使用的是mvc4,但是由于需要FileResult和javascriptResult同时可以输出,我这边定义了ActionResult做为输出,其中的代码很简单,就是让datatable可以在excel的流写入,然后通过File方法保存浏览器。

/// <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 < 30)
                {
                    //Response.Redirect("/Home/Index");
                    return this.Content("<script>alert('30分钟内不能重复导出到excel!')</script>");
                   
                    return this.Content("alert('作成功')", "application/x-javascript");
                    return Content("alert('购物订单成功处理!');", "text/javascript");
                    //string script = string.Format("alert('库存不足! ({0})');", ":");
                    //return JavaScript(script);
                    return JavaScript("alert('30分钟内不能重复导出到excel!');");
                    //return Content("<font color='red'>你好啊ContentResult</font>");
                    // return new EmptyResult(); 

                }
            }
            //延迟30分钟再可以提交
         
            string sql = "SELECT  [UserID],[UserCode],[UserName],[ParentID],[Position],[Mobile],[Email],[Levels],[AttentionTime]FROM Users WHERE CreateStatus = 1 AND(AttentionState = 1); ";
            DataTable dt = ObjectContainer.Instance.GetObject<ISqlExportService>().GetDataTableFromSql(Request, sql);

            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet  
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            //row1.RowStyle.FillBackgroundColor = "";  
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
            }
            //将数据逐步写入sheet1各个行  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    rowtemp.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString().Trim());
                }
            }
            string strdate = DateTime.Now.ToString("yyyyMMddhhmmss");//获取当前时间  
            // 写入到客户端   
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            DateTime = DateTime.Now;
            xele.SetAttributeValue("content", DateTime);
            xele.Save(AppDomain.CurrentDomain.BaseDirectory + "Resource\\Config\\DatetimeConfig.xml");
            return File(ms, "application/vnd.ms-excel", strdate + "Excel.xls");
        }

其中做了30分钟的重复登录限制,如果输出一次再点击的话低于30分钟会不允许并且弹出窗口提示,这是问题的关键,那我这个control还会执行,弹出后希望保持在当前页面,我最先想到的在Onsucess中定义JavaScript的函数来进行回退跳转,这个方法一直不能执行。

    function refresh(e) {
       
      alert("test"); 


    }
  
    function SearchSqlToExcel() {


        var parameters = {
            Sheetname: "User",
            fileName: "e:\\a.xls"
        };
        $.ajax({
            type: "POST",
            url: "@Url.Content("~/SqlExportService/DownLoadExcel")",
            contentType: "application/json",
            data: JSON.stringify(parameters)
        });
     
    }

</script>

@using (Ajax.BeginForm("DownLoadExcel", "SqlExportService", new AjaxOptions{ HttpMethod = "Post", OnSuccess = "refresh", OnBegin = "" }))
{
    <input type = "submit" value = "导出excel" />
}

后来找过很多资料,也在本博客中转载贴出,研究了ContentResult和EmptyResult以及JavascriptResult的各种输出,最后说<script type=”text/javascript” src=”@Url.Content(“~/Resource/Scripts/jquery.unobtrusive-ajax.js”)”></script>这段没有写,之后又说jquery要1.8.3,再后来也把web.config的<add key=”UnobtrusiveJavaScriptEnabled” value=”true” />也加到Appsetting,refresh终于可以执行了,但是文件却不能下载了。最初的目的实现不了了,后来只能再想起他办法。



版权声明:本文为orichisonic原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。