我们知道,JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但在js中 生成一个form,用这个form提交参数,并返回“流”类型的数据。在实现过程中,页面也没有进行刷新。

注意,如果服务器端是Spring MVC,则该server端必须支持 post方法且 content type 是 "application/x-www-form-urlencoded"

下面的例子均已调试通过。

前端JS页面例子:

mp.jsp

 manipulationHistory.downloadData = function() {//定义一个form表单var myform = $("<form></form>");myform.attr('method','post')myform.attr('action',"/manipulationHistory/exportManipulationInfo");var myProductId = $("<input type='hidden' name='productId' />")myProductId.attr('value',$("#query-param-product-id").val());var myPurchaseOrderId = $("<input type='hidden' name='purchaseOrderId' />") myPurchaseOrderId.attr('value',$("#query-param-dispatched-po").val());var myWarehouseId = $("<input type='hidden' name='warehouseId' />") myWarehouseId.attr('value', $("#query-param-warehouse-id").val());var myRelatedOrderId = $("<input type='hidden' name='relatedOrderId' />") myRelatedOrderId.attr('value', $("#query-param-order-id").val());var myUpdateReason = $("<input type='hidden' name='updateReason' />") myUpdateReason.attr('value', $("#query-param-update-reason").val());var myStartTime = $("<input type='hidden' name='startTime' />") myStartTime.attr('value', $("#operate-time-start-value").val());var myEndTime = $("<input type='hidden' name='endTime' />") myEndTime.attr('value', $("#operate-time-end-value").val());myform.append(myProductId);myform.append(myPurchaseOrderId); myform.append(myWarehouseId); myform.append(myRelatedOrderId); myform.append(myUpdateReason); myform.append(myStartTime); myform.append(myEndTime);myform.appendTo('body').submit(); //must add this line for higher html spec      };

后台server端的java代码如下(用SPring MVC来支持)

/** Ajax not support stream response message, so front page need to use form* to submit request with APPLICATION_FORM_URLENCODED*/@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })@RequestMapping(value = "/exportManipulationInfo", method = RequestMethod.POST)@ResponseBodypublic boolean exportManipulationInfo(HttpServletRequest request, HttpServletResponse response) {ManipulationInfoQuery manipulationInfoQuery = generateMHQuery(request);LOG.info("[IMS_INFO][exportManipulationInfo] received request: " + JsonHelper.toJson(manipulationInfoQuery));List<ManipulationInfo> resultList = manipulationHistoryPageService.getManipulationInfoListWithoutPage(manipulationInfoQuery);if (null == resultList || resultList.isEmpty()) {LOG.info(" no data retrieved for query: " + JsonHelper.toJson(manipulationInfoQuery));}return downLoadsExcel(resultList, response);}private ManipulationInfoQuery generateMHQuery(HttpServletRequest request) {ManipulationInfoQuery resultQuery = new ManipulationInfoQuery();resultQuery.setProductId(request.getParameter("productId"));resultQuery.setPurchaseOrderId(request.getParameter("purchaseOrderId"));String warehouseID = request.getParameter("warehouseId");if (StringUtils.isNotBlank(warehouseID)) {resultQuery.setWarehouseId(Integer.parseInt(warehouseID));} else {resultQuery.setWarehouseId(null);}resultQuery.setRelatedOrderId(request.getParameter("relatedOrderId"));resultQuery.setUpdateReason(request.getParameter("updateReason"));resultQuery.setStartTime(request.getParameter("startTime"));resultQuery.setEndTime(request.getParameter("endTime"));resultQuery.setPageInd(null);resultQuery.setPageSize(null);return resultQuery;}private boolean downLoadsExcel(List<ManipulationInfo> dataList, HttpServletResponse response) {FileOutputStream fos = null;try {HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("ManipulationInfo_details");sheet.setDefaultColumnWidth(40);HSSFCellStyle style = wb.createCellStyle();style.setAlignment(HSSFCellStyle.ALIGN_LEFT);String fileName = "ManipulationInfoData-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";fos = new FileOutputStream(fileName);// column nameString[] label = { "index", "productId", "productName", "warehouseId", "warehouseName", "dispatchedPo", "relatedOrderId", "updateField", "action","result", "updateReason", "operator", "operateTime" };int columnNum = label.length;// set title column at line 0HSSFRow titleRow = sheet.createRow((int) 0);// the most left column is index of columnHSSFCell titleCell = null;for (int n = 0; n < columnNum; n++) {titleCell = titleRow.createCell(n);titleCell.setCellType(HSSFCell.CELL_TYPE_STRING);titleCell.setCellValue(label[n]);titleCell.setCellStyle(style);}if (null != dataList && !dataList.isEmpty()) {for (int rowIndex = 0; rowIndex < dataList.size(); rowIndex++) {ManipulationInfo item = dataList.get(rowIndex);/** the line 0 is title line,so actual data line begins from* the next one line.*/HSSFRow row = sheet.createRow(rowIndex + 1);String rowData[] = { item.getProductId(), item.getProductName(), item.getWarehouseId().toString(), item.getWarehouseName(),item.getDispatchedPo(), item.getRelatedOrderId(), item.getUpdateField(), item.getAction(), item.getResult().toString(),item.getUpdateReason(), item.getOperator(), item.getOperateTime() };// create the most left column as index columnHSSFCell cell = row.createCell(0, HSSFCell.CELL_TYPE_NUMERIC);cell.setCellValue(rowIndex + 1);cell.setCellStyle(style);// create the remaining cells at the same linefor (int columnIndex = 1; columnIndex < columnNum; columnIndex++) {cell = row.createCell(columnIndex, HSSFCell.CELL_TYPE_STRING);cell.setCellValue(rowData[columnIndex - 1]);cell.setCellStyle(style);}}} else {LOG.info(" no data retrieved");}// set all columns to automatically adjust column widthfor (int i = 0; i < columnNum; i++) {sheet.autoSizeColumn(i);}wb.write(fos); // write workbook into file .xlsfos.flush(); // flush buffer to filefos.close(); // remember to close itif (wb != null) {response.reset();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes(), "iso-8859-1"));OutputStream out = response.getOutputStream();wb.write(out);out.flush();out.close();}} catch (Exception e) {LOG.error( downLoadsExcel exception:" + e);return false;} finally {if (fos != null) {try {fos.close();} catch (IOException e) {LOG.error(" close FileOutputStream error:" + e);return false;}}}return true;}

在上面的JAVA后端代码中,注意没有@RequestBody来修饰传入参数,这是因为如下说明:

关于@ResponseBody,@RequestBody,@PathVariable比较通俗的解释就是:
@PathVariable主要是用来处理URl路径的问题,利用@PathVariable可以是实现在URL路径中实现参数的隐藏效果。
@RequestBody主要是用来处理请求类型转换问题,例如可以把json字符串通过配置自动转换为对象之类的。
@ResponseBody主要是用来处理返回类型转换问题,例如可以把json字符串通过配置自动转换为对象之类的。
一般@ResponseBody,@RequestBody都是用来处理json和xml数据类型,不能用于传统的html解析,因为@ResponseBody,@RequestBody都只是获取内容而已,并不是整个html,所以在有用到json或者xml数据类型传输的时候才可以考虑使用@ResponseBody,@RequestBody这两个注解,否则不要使用。

一个不错的连接是:

http://blog.csdn.net/linzhiqiang0316/article/details/52328153

JQuery 中 AJAX 如何实现 Excel 文件 下载相关推荐

  1. 使用Jquery中ajax实现上传文件

    html: <input type="file" name="uploadFile" id="uploadFile"> jq: ...

  2. jquery中ajax加载js和json文件

    全栈工程师开发手册 (作者:栾鹏) jquery系列教程6-AJAX全解 jquery中ajax加载js文件 jquery中ajax加载js文件的函数为getScript() 代码如下: $.getS ...

  3. jQuery中的ajax、jquery中ajax全局事件、load实现页面无刷新局部加载、ajax跨域请求jsonp、利用formData对象向服务端异步发送二进制数据,表单序列化(异步获取表单内容)

    jQuery中使用ajax: 在jQuery中使用ajax首先需要引入jQuery包,其引入方式可以采用网络资源,也可以下载包到项目文件中,这里推荐下载包到文件中:市面上有多个版本的jQuery库,这 ...

  4. [转]Jquery中AJAX错误信息调试参考

    下面是Jquery中AJAX参数详细列表: 参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址. type String (默认: "GET") 请求 ...

  5. jquery中ajax完整例子get,jq的ajax方法,jquery中ajax完整例子

    jq的ajax方法,jquery中ajax完整例子 相较与js异步对象的繁琐,jq的ajax对象结构更加清晰 一:ajax对象简述 ajax(Asynchronous JavaScript and X ...

  6. DataTable中的数据导出Excel文件

    DataTable中的数据导出Excel文件 View Code ///<summary> /// 将DataTable中的数据导出到指定的Excel文件中 ///</summary ...

  7. jquery中ajax应用——get()和post()

    全栈工程师开发手册 (作者:栾鹏) jquery系列教程6-AJAX全解 jquery中ajax应用--get()和post() get和post发送数据的方式不同,但是在jquery的ajax中这种 ...

  8. jquery中ajax应用——load()函数

    全栈工程师开发手册 (作者:栾鹏) jquery系列教程6-AJAX全解 jquery中ajax应用之load()函数 $(selector).load(URL,data,callback)函数通常来 ...

  9. 在vue中把数据导出Excel文件

    在vue中把数据导出Excel文件 第一次尝试写文章 在vue中把数据导出成Excel格式的文件,话不多,上代码: 第一步我们要先安装几个集成的插件 npm install -S file-saver ...

最新文章

  1. anaconda 设置python3为主_关于在Windows、Linux和Mac上安装设置Python的问题
  2. 电厂运维的cis数据_【面向运行人员的电站智能运维管家系统】
  3. java学习(六)数据类型分类
  4. JVM调优技巧与经验
  5. Linux系统利用Crontab命令实现定时重启
  6. (王道408考研数据结构)第八章排序-第二节:直接插入排序和希尔排序
  7. DB2数据库中DB2字符串类型
  8. python 时间模块 time datetime calendar
  9. android 定制输入法,QQ输入法Android 4.3全新升级 实现私人定制输入
  10. OpenGL中投影矩阵(Projection Matrix)详解
  11. ​突破 1nm!台积电祭出“半金属”取代硅材料;搜狗发布手语 AI 合成主播;iOS 微信 8.0.6 版本更新|极客头条...
  12. 你要好好的---歌词
  13. 《编译原理及实践教程》第一章学习笔记
  14. Pix2Pix代码解析
  15. 腾讯云短信服务申请+测试
  16. python网页自动化填写-用python-webdriver实现自动填表
  17. 女孩子没有事业就只能痛苦
  18. 五分钟告诉你什么是爬虫?
  19. openmv图像格式不支持问题解决方案
  20. 排序法学习之插入排序(python3实现)

热门文章

  1. oracle jdbc中文,oracle jdbc
  2. gpu显卡dos测试软件,GpuTest显卡测试软件 For Win
  3. 国外iPhone 3GS 越狱 iOS 4.1视频放出
  4. 基于SSH开发国家矿产资源管理系统
  5. 复习 |链表基本操作(逆序)
  6. linux怎么修改ftp密码
  7. ASP .NET(基于.NET 6.0)源码解读
  8. T265/D435i相机和相机与IMU参数获取,也可以通过realsense-viewer直接获取
  9. php168上传空间常见问题
  10. 比武招亲的java游戏,比武招亲百度版本下载