有時候導出Excel時需要根據某些條件篩選數據,然后將數據通過NPOI生成Excel並導出。組織數據時可以通過放到一個表單中,某些場景是使用腳本(如:jquery)組織一個form(通過字符串拼接),然后將這個from的轉換成jquery對象或者Dom對象,再調用對應的submit方法。
例子如下,有一個html頁面
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<input type="button" value="導出Excel" id="btnExport" />
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript"> $(function () { $("#btnExport").click(function () { var formHtml = "<form action='DownLoadHandler.ashx' method='post' target='_blank'>"; formHtml += "<input type='hidden' name='username' value='admin' />"; formHtml += "<input type='hidden' name='password' value='abc' />"; formHtml += "</form>"; $(formHtml).submit(); }); }); </script>
</body>
</html>
這里是ASP.NET web應用程序,有一個一般處理程序,它通過判斷篩選條件(這里是用戶名和密碼,實際當中可能是某些查詢條件,用戶向數據庫查詢數據等),然后導出Excel
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary>
/// DownLoadHandler 的摘要說明 /// </summary>
public class DownLoadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.Form["username"] == "admin" && context.Request.Form["password"] == "abc") { context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment;filename=persons.xlsx"); byte[] bytes = File.ReadAllBytes(context.Server.MapPath("~/SysFolder/Persons.xlsx")); context.Response.BinaryWrite(bytes); } else { context.Response.ContentType = "text/plain"; context.Response.Write("沒有找到數據,導出excel失敗"); } } public bool IsReusable { get { return false; } } } }
通過瀏覽器瀏覽,點擊按鈕發現沒有提交表單,網絡監視里沒有發出請求

查看開發人員工具中的控制台,發現提示Form submission canceled because the form is not connected

該問題需要將組織的form追加到文檔的body中,然后再提交,於是修改代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<input type="button" value="導出Excel" id="btnExport" />
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript"> $(function () { $("#btnExport").click(function () { var formHtml = "<form action='DownLoadHandler.ashx' method='post' target='_blank'>"; formHtml += "<input type='hidden' name='username' value='admin' />"; formHtml += "<input type='hidden' name='password' value='abc' />"; formHtml += "</form>"; var form = $(formHtml); $(document.body).append(form); form.submit(); }); }); </script>
</body>
</html>
刷新頁面,再次提交,發現正常
參考鏈接:https://stackoverflow.com/questions/42053775/getting-error-form-submission-canceled-because-the-form-is-not-connected
