<li>
<button class="whiteBg btn2" onclick="doExp(1);return false; ">
<i class="fa fa-save (alias) m-r-xs" ></i>導出所有工單
</button>
</li>
<li>
<button class="whiteBg btn2" onclick="doExp(2);return false; ">
- <i class="fa fa-file-text-o m-r-xs"></i>導出所選工單
</button>
</li>
2.1 調用的js方法如下 , 通過
url傳值的方式get請求到SpringMVC的控制器.
function expExcel(){
//alert("expExcel");
var url="../user/expExcel?loginName=${user.loginName}&userName=${user.userName}&moblie=${user.mobile}";
//alert(url);
window.location.href=url;
}
- 或者用
- function exportExcel(){ if(flag){ flag = false; window.location.href = "${ctx}/rpt/4gSite/empToExcel";setTimeout(function(){flag = true;},2000); } }
- 或者, 都是一樣的用法.
- $(function(){ exp=function(){ var query_time=$('#query_time').val(); window.location.href="../../doExp?query_time="+query_time; } });
window.location.href 為本頁面跳轉請求 (js中在本頁面調整,上頁面調整之類的用法可以延伸閱讀), 對應的控制器代碼如下, 從DB獲取數據后生成對應的文件,然后通過
ServletUtils
.
flushExcelOutputStream
輸出流寫給瀏覽器.
@RequestMapping("/expToExcel")
public void expToExcel(HttpServletRequest request, HttpServletResponse response) {
UserContext uc = this.getUserContext(request);
String loginName = request.getParameter("loginName");
String userName= request.getParameter("userName");
String moblie= request.getParameter("moblie");
- User user=new User();
user.setLoginName(loginName);
user.setUserName(userName);
user.setMobile(moblie);
List<User> users=this.userService.getListBy(user,uc);
ExcelExportUtils2<User> exUser = new ExcelExportUtils2<User>();
HSSFWorkbook workbook = exUser.exportExcel(new HSSFWorkbook(),"用戶列表清單", users);
ServletUtils.flushExcelOutputStream(request, response, workbook,
"用戶列表清單_"+DateUtil.formatDateToString("yyyyMMdd", new Date()));
}
對應
S
ervletUtils.
flushExcelOutputStream
的代碼 【
ServletUtils的代碼可以參考springside或者jeesite】
】
分兩個步驟,
1判斷不同的瀏覽器,對文件名的中文字符進行編碼。
2然后利用輸出流將文件寫出給瀏覽器。
/**
* 導出Excel,使用自定義的名字作為文件名
* @param request
* @param response
* @param dataList
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static void flushExcelOutputStream(HttpServletRequest request, HttpServletResponse response,
HSSFWorkbook workbook,String fileName) {
String userAgent = request.getHeader("User-Agent");
String newFileName = null;
try {
fileName = URLEncoder.encode(fileName, "UTF8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
if (userAgent != null) {
userAgent = userAgent.toLowerCase();
// IE瀏覽器,只能采用URLEncoder編碼
if (userAgent.indexOf("msie") != -1) {
newFileName = "filename=\"" + fileName + ".xls\"";
}
// Opera瀏覽器只能采用filename*
else if (userAgent.indexOf("opera") != -1) {
newFileName = "filename*=UTF-8''" + fileName +".xls";
}
// Safari瀏覽器,只能采用ISO編碼的中文輸出
else if (userAgent.indexOf("safari") != -1) {
try {
newFileName = "filename=\""
+ new String(fileName.getBytes("UTF-8"), "ISO8859-1")
+ ".xls\"";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// Chrome瀏覽器,只能采用MimeUtility編碼或ISO編碼的中文輸出
else if (userAgent.indexOf("applewebkit") != -1) {
try {
fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
newFileName = "filename=\"" + fileName + ".xls\"";
}
// FireFox瀏覽器,可以使用MimeUtility或filename*或ISO編碼的中文輸出
else if (userAgent.indexOf("mozilla") != -1) {
newFileName = "filename*=UTF-8''" + fileName +".xls";
}
}
//文件名編碼結束。
response.setHeader("Content-Disposition", "attachment;" + newFileName); // 這個很重要
ServletUtils.setDisableCacheHeader(response);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
workbook.write(out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out != null){
try {
out.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
}
}
2.2 以上都是基於url傳值的方式(GET方式)就參數傳給后台處理.
這是比較常用的方式.
問題有2個
1 參數過多的話傳遞麻煩.
2 get方式傳遞的長度有限制
針對 傳參麻煩可以通過以下方式改進, 將表單序列化
window.location.href = "../../../../download?"+$('#form_Report').serialize();
window.location.href = "../../../../download?userName=${user.userName}"+"&"+$('#form_Report').serialize();
注意序列化中用到的是serialize().
注意serialize() 和serializearray()的不同
針對2的問題,只能通過post方式提交來規避.
3.1 實現方式1
js可以直接將表單table直接提交的方式來傳遞參數給SpringMVC的控制器: 效果也一樣的. 這里要注意table的action被修改了. 表單查詢調用時需注意.
//這里jeesite使用jbox插件.調用
top
.$.jBox.confirm 在父頁面上彈出確認框,然后還是使用js
更改form的action並提交$("#submitForm").attr("action", url);
觸發submit事件,再提交表單$("#submitForm").submit();
<input id="btnExport" class="btn btn-primary" type="button" value="導出"/>
$(document).ready(function() {
// 表格排序
tableSort({callBack : page});
$("#btnExport").click(function(){
top.$.jBox.confirm("確認要導出用戶數據嗎?","系統提示",function(v,h,f){
if(v == "ok"){
$("#searchForm").attr("action","${ctx}/sys/user/export").submit();
}
},{buttonsFocus:1});
top.$('.jbox-body .jbox-icon').css('top','55px');
});
$("#btnImport").click(function(){
$.jBox($("#importBox").html(), {title:"導入數據", buttons:{"關閉":true},
bottomText:"導入文件不能超過5M,僅允許導入“xls”或“xlsx”格式文件!"});
});
});
3.2 本方法和3.1大同小異, 都是通過表單的方式來提交.3.2模擬一個表單將參數填入創建input
通過js模擬表單提交
調用如下
DownLoadFile2({url:'../../../alarm/doExp',data:ids}); //ids為選中的數據的id如拼接字符串,如: 1,2,3,55,333,123,
所調用方法如下
//提交表單
var DownLoadFile = function (options) {
var config = $.extend(true, { method: 'post' }, options);
var $iframe = $('<iframe id="down-file-iframe" />');
var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
$form.attr('action', config.url);
for (var key in config.data) {
$form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$iframe.append($form);
$(document.body).append($iframe);
$form[0].submit();
$iframe.remove();
};
//提交參數
var DownLoadFile2 = function (options) {
var config = $.extend(true, { method: 'post' }, options);
var $iframe = $('<iframe id="down-file-iframe" />');
var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
$form.attr('action', config.url);
$form.append('<input type="hidden" name="ids" value="' + options.data + '" />');
$iframe.append($form);
$(document.body).append($iframe);
$form[0].submit();
$iframe.remove();
};
如IE8下中文存在問題可以優化為
var DownLoadFile = function (options) {
var config ={ method: 'post' };
var $form = $('<form method="' + config.method + '" />');
$(document.body).append($form);
$form.attr('action', options.url);
for (var key in options.data) {
$form.append('<input type="hidden" name="' + key + '" value="' + options.data[key] + '" />');
}
$form[0].submit();
$form.remove();
};
調用方法舉例
var DownLoadFile = function (options) {
var config ={ method: 'post' };
var $form = $('<form method="' + config.method + '" />');
$(document.body).append($form);
$form.attr('action', options.url);
for (var key in options.data) {
$form.append('<input type="hidden" name="' + key + '" value="' + options.data[key] + '" />');
}
$form[0].submit();
$form.remove();
};
后台方法一樣, 控制器輸出流寫文件即可.
備注:
- $(selector).serialize() 序列表表格內容為字符串,用於 Ajax 請求。可以對整個form,也可以只針對某部分。
$('#form').submit(function(event){
event.preventDefault();
$.ajax({
url:' ',
type:'post',
data:$("form").serialize(),
}
- $(selector).serializeArray()
serializeArray() 方法序列化表單元素(類似 .serialize() 方法),返回 JSON 數據結構數據。
注意:此方法返回的是 JSON 對象而非 JSON 字符串。需要使用插件或者第三方庫進行字符串化操作。
返回的 JSON 對象是由一個對象數組組成的,其中每個對象包含一個或兩個名值對 —— name 參數和 value 參數(如果 value 不為空的話)。舉例來說:
[
{name: 'firstname', value: 'Hello'},
{name: 'lastname', value: 'World'},
{name: 'alias'}, // 值為空
]
.serializeArray() 方法使用了 W3C 關於 successful controls(有效控件) 的標准來檢測哪些元素應當包括在內。特別說明,元素不能被禁用(禁用的元素不會被包括在內),並且元素應當有含有 name 屬性。提交按鈕的值也不會被序列化。文件選擇元素的數據也不會被序列化。
該方法可以對已選擇單獨表單元素的對象進行操作,比如 <input>, <textarea>, 和 <select>。不過,更方便的方法是,直接選擇 <form> 標簽自身來進行序列化操作。
$("form").submit(function() {
console.log($(this).serializeArray());
return false;
});
上面的代碼產生下面的數據結構(假設瀏覽器支持 console.log):
[
{
name: a
value: 1
},
{
name: b
value: 2
},
{
name: c
value: 3
},
{
name: d
value: 4
},
{
name: e
value: 5
}
]
- $.params() $.param()方法是serialize()方法的核心,用來對一個數組或對象按照key/value進行序列化。
序列化一個 key/value 對象:
var params = { width:1900, height:1200 };
var str = jQuery.param(params);
$("#results").text(str);
結果:
width=1680&height=1050
