標籤:xlsx == position round export folder hid method hidden
有時候匯出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
Jquery組織Form表單提交之Form submission canceled because the form is not connected