spring mvc 服务器端生成文件后下载

spring mvc 服务器端生成文件后下载

前端发起请求,后端服务器接收参数,查询数据,使用poi组件 生成excel 返回给客户端

使用jquery ajax 的方式无法实现,需要采用动态生成form表单的再submit的方式

前端代码如下:

$.downloadByPost = function(url, data) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        $.each(data.split('&'), function() {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="'
                    + decodeURIComponent(pair[1]) + '" />';
        });
        $(
                '<form accept-charset="UTF-8" action="' + url + '" method="post">' + inputs + '</form>').appendTo('body').submit()
                .remove();
    }
    ;
};

调用方式:

var url = "../" + exportUrl + "?starttime1="+starttime1+
    "&starttime2="+starttime2+"&endtime1="+endtime1+"&endtime2="+endtime2+"&type="+type;
postData={user:'张三'}
$.downloadByPost(url, postData);

需要注意的是jQuery.param中使用了encodeURIComponent解决中文传递的问题,但是在我的spring mvc 中已经设置了中文的filter,在tomcat的server.xml中也设置了

<Connector port="8080" redirectPort="8443" protocol="HTTP/1.1" connectionTimeout="20000" URIEncoding="UTF-8"/>

所以不需要encode了,本来想着自己定义一个param函数,但是比较麻烦。后来想到在encode之后,向form表单中的input赋值的时候,再解码不就可以了么,于是

inputs += '<input type="hidden" name="' + pair[0] + '" value="'
                    + decodeURIComponent(pair[1]) + '" />';

后台代码:

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;


@RequestMapping("exportnetwork") @Transactional public @ResponseBody AjaxResult export(Model model, Integer type,Entity info, Integer starttime1, Integer endtime1, Integer starttime2, Integer endtime2) { String filepath = ""; String filename = ""; String realPath = request.getServletContext().getRealPath("/WEB-INF/expExcel"); filepath = realPath + "\\" + "1.xlsx"; filename = "1"; List<Entity> list = Lists.newArrayList(); List<String> dids = Lists.newArrayList(); list = cmsAssetsService.searchassetinfos(dids, info, starttime1, endtime1, starttime2, endtime2); File fi = new File(filepath); try { Workbook wb = WorkbookFactory.create(new FileInputStream(fi)); Sheet sheet = wb.getSheetAt(0); CellStyle style = wb.createCellStyle(); style.setWrapText(true);// 设置自动换行 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式 Font headerFont = wb.createFont(); // 创建字体样式 headerFont.setFontName("宋体"); // 设置字体类型 headerFont.setFontHeightInPoints((short) 18); // 设置字体大小 style.setFont(headerFont); // 为标题样式设置字体样式 CellStyle style1 = wb.createCellStyle(); style1.setWrapText(true);// 设置自动换行 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式 // 创建第0行 也就是表头 Row row1 = sheet.createRow(0); row1.setHeightInPoints(35);// 设置表头高度 Cell cell = row1.createCell(0); cell.setCellValue(filename); cell.setCellStyle(style); Cell cell01 = row1.createCell(13); cell01.setCellValue("导出人: " + cmsSession.getName()); cell01.setCellStyle(style1); Cell cell02 = row1.createCell(14); cell02.setCellValue("时间: " + DateUtils.format(new Date(), "yyyy.MM.dd")); cell02.setCellStyle(style1); if (null != list && list.size() > 0) { int i = 1; for (Entity asset : list) { Row row = sheet.createRow(1 + i); Cell cell0 = row.createCell(0); cell0.setCellValue(i++); cell0.setCellStyle(style1); Cell cell1 = row.createCell(1); cell1.setCellValue(asset.getName()); cell1.setCellStyle(style1); } } // 将文件存到浏览器设置的下载位置 response.setContentType("application/ms-excel;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(filename + ".xlsx", "UTF-8")))); OutputStream out; out = response.getOutputStream(); wb.write(out);// 将数据写出去 AjaxResult result = new AjaxResult("success", "导出成功!"); return result; } catch (Exception e) { e.printStackTrace(); AjaxResult result = new AjaxResult("erroe", "导出出错!"); return result; } }

导出excel的jar包使用的是poi 3.12 ,需要注意的是还需要xmlbeans组件,版本是2.6

posted @ 2018-07-27 16:59  八方鱼  阅读(738)  评论(0)    收藏  举报