步骤:
1.在展示页list.jsp上加:
<grid:toolbar function="exports"/>
2.在curdtools_jqgrid.js里加exports方法:
/**
* 导出
* @param gridId
*/
function exports(gridId) {
var queryParams = {};
var queryFields=$('#queryFields').val();
queryParams['queryFields'] = queryFields;
//普通的查询
$('#' + gridId + "Query").find(":input").each(function() {
var val = $(this).val();
if (queryParams[$(this).attr('name')]) {
val = queryParams[$(this).attr('name')] + "," + $(this).val();
}
queryParams[$(this).attr('name')] = val;
});
// 普通的查询
$('#' + gridId + "Query").find(":input").each(function() {
var condition = $(this).attr('condition');
if (!condition) {
condition = "";
}
var key = "query." + $(this).attr('name') + "||" + condition;
queryParams[key] = queryParams[$(this).attr('name')];
});
//刷新
//传入查询条件参数
/* $("#"+gridId).jqGrid('setGridParam',{
datatype:'json',
url:'shopcart/exports',
postData:queryParams, //发送数据
page:1
}).trigger("reloadGrid"); //重新载入
*/
var result = $.param(queryParams);
location.href="shopcart/exports?"+result;
}
不用/* */注释掉的那几行代码是因为返回的文件流无法下载,不弹出下载框,也没有下载到默认路径
param()方法创建数组或对象的序列化表示,该序列化值可在进行AJAX请求时在URL查询字符串中使用,即可以将JSON格式的参数转换为URL后所跟参数的格式。
3.src/main/resources下i18n文件夹下得messages.properties文件内添加:
sys.common.exports=导出
4.cn.jeeweb.core.tags.grid.DataGridToolbarTag.java中修改:
private static String[] INNER_DEFAULT_FUNCTION = { "create", "update", "delete", "search", "reset","exports" };
在inner_default_function中添加exports方法;
修改dealDefault方法:
private void dealDefault(DataGridTag parent) {
if (!StringUtils.isEmpty(this.function) && isFunction(this.function)) {
// 预处理Url问题
if (StringUtils.isEmpty(url)) {
String url = "";
if (this.function.equals("delete")) {
url = parent.getBaseUrl() + "/batch/delete";
} else if (this.function.equals("update")) {
url = parent.getBaseUrl() + "/{id}/" + this.function;
}else {
url = parent.getBaseUrl() + "/" + this.function;
}
staticAttributes.put("url", url);
//System.out.println("url:"+url);
}
if (StringUtils.isEmpty(title)) {
String title = "sys.common." + this.function;
staticAttributes.put("title", MessageUtils.getMessageOrSelf(title));
}
if (StringUtils.isEmpty(this.icon)) {
String icon = "";
if (this.function.equals("create")) {
// btn-info
icon = "fa-plus";
} else if (this.function.equals("update")) {
icon = "fa-file-text-o";
} else if (this.function.equals("delete")) {
icon = "fa-trash-o";
} else if (this.function.equals("search")) {
icon = "fa-search";
} else if (this.function.equals("reset")) {
icon = "fa-refresh";
}else if(this.function.equals("exports")){
icon = "fa-file-excel-o";//新添,exports的图标
}
staticAttributes.put("icon", icon);
}
if (StringUtils.isEmpty(this.btnclass)) {
String btnclass = "";
if (this.function.equals("create")) {
// btn-info
btnclass = "btn-primary";
} else if (this.function.equals("update")) {
btnclass = "btn-success";
} else if (this.function.equals("delete")) {
btnclass = "btn-danger";
} else if (this.function.equals("search")) {
btnclass = "btn-info";
} else if (this.function.equals("reset")) {
btnclass = "btn-warning";
} else {
btnclass = "btn-info";
}
staticAttributes.put("btnclass", btnclass);
}
if (this.function.equals("search") || this.function.equals("reset")|| this.function.equals("exports")) {
staticAttributes.put("layout", "right");
}//或条件加上exports判断
}
}
5.对应的Controller层添加方法exports:(可直接导出为excel文件)
@RequestMapping(value = "exports", method = { RequestMethod.GET, RequestMethod.POST })
@PageableDefaults(sort = "id=desc")
private void exports(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 预处理
QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
//listNoPage()方法返回符合查询条件的所有数据,不分页
PageJson<ShopCart> pagejson = new PageJson<ShopCart>(shopCartService.listWithNoPage(queryable,entityWrapper));
List<ShopCart> list = pagejson.getResults();
//对需要导出的结果进行封装
JSONObject json = new JSONObject();
for(int i=0;i<list.size();i++){
JSONArray array = new JSONArray();
ShopCart sc = list.get(i);
array.add(sc.getPackName());
array.add(sc.getUserName());
array.add(sc.getQuantity());
json.put(i, array);
}
try {
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
for(int i = 1;i<=json.size();i++){
JSONArray array = json.getJSONArray(String.valueOf(i-1));
String[] data = new String[array.size()];
Object[] ar = array.toArray();
for(int j=0;j<array.size();j++){
data[j] = ar[j]+"";
}
ExcelWrite.pointDataInsert(sheet,data,i);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
byte[] content = baos.toByteArray();
response.reset();
response.setContentType("content-disposition");
response.addHeader("Content-Disposition", "attachment; filename=\""+ExcelWrite.fileNameSolve(request,"12345")+".xlsx\"");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(content, 0, content.length);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
其中的pointDataInsert()方法为:
/**
* 填充单元格
*
* @date 2015年8月21日
* @author ren
* @param sheet
* @param point
* @param columns
* @param startRow
*/
public static void pointDataInsert(Sheet sheet, String[] columns, int startRow) {
Row row = sheet.createRow(startRow);
for (int i = 0; i < columns.length; i++) {
String value = columns[i];
if (value != null && !value.equalsIgnoreCase("null")) {
row.createCell(i, Cell.CELL_TYPE_STRING).setCellValue(value.toString());
}
}
}
以及调用的ExcelWrite类中的方法:
//下载文件中文乱码解决
public static String fileNameSolve(HttpServletRequest request,String beforeFileName) throws UnsupportedEncodingException{
boolean isMSIE = isMSBrowser(request);
if (isMSIE) {
beforeFileName = URLEncoder.encode(beforeFileName, "UTF-8");
}else {
beforeFileName = new String(beforeFileName.getBytes("UTF-8"), "ISO-8859-1");
}
return beforeFileName;
}
private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
//判断浏览器是否是微软浏览器
public static boolean isMSBrowser(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
for (String signal : IEBrowserSignals) {
if (userAgent.contains(signal))
return true;
}
return false;
}
至此,查询结果可在浏览器中下载了。