Springmvc 生成并且下载文件--直接在浏览器下载。

首先,我有一个jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title







很久不玩,都不记得jsp怎么配得了。


		
		
	



这是一个访问用的Controller:用来跳转到下载页面。

@RequestMapping("testjsp")
    public ModelAndView test(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("status");
        return modelAndView;
    }


这是一个下载的Controller

@RequestMapping("testDownload")
    public String testDownload(HttpServletRequest request, HttpServletResponse response/*, @RequestBody PieceCostParam pieceCostParam*/) throws Exception{
        PieceCostParam pieceCostParam = new PieceCostParam();
        PieceCostQuery pieceCostQuery = new PieceCostQuery();
        pieceCostQuery.setCompanyName("杭州电子放假大学");
        pieceCostParam.setPieceCostQuery(pieceCostQuery);
        return excelExportService.testDownload(request, response, pieceCostParam);
    }



这是service:
@Override
    public String testDownload(HttpServletRequest request, HttpServletResponse response, PieceCostParam pieceCostParam) throws Exception{
        String fileName="excel文件";
        //填充projects数据
        List projects=costRelatedService.getAllPieceCost(pieceCostParam);
        List> list=createExcelRecord(projects);
        String columnNames[]={"序号","机构名称","购买时间","数据包名称","购买线索条数","线索单价","线索收费"};//列名
        String keys[]    =     {"id","name","purcahseTime","packName","num","cost","sumcost"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list,keys,columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数,可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }


    private List> createExcelRecord(List projects) {
        List> listmap = new ArrayList>();
        Map map = new HashMap();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        PieceCostVO project=null;
        for (int j = 0; j < projects.size(); j++) {
            project=projects.get(j);
            Map mapValue = new HashMap();
            mapValue.put("id", j);
            mapValue.put("name", project.getCompanyName());
            mapValue.put("purcahseTime", project.getPurchaseTime());
            mapValue.put("packName", project.getDataPackName());
            mapValue.put("num", project.getDataSum());
            mapValue.put("cost", project.getDataCost());
            mapValue.put("sumcost", project.getCostSum());
            listmap.add(mapValue);
        }
        return listmap;
    }

这是ExcelUtil类:
/**
 * 导出Excel文档工具类
 * [@author](http://my.oschina.net/arthor) 那位先生
 * [@date](http://my.oschina.net/u/2504391) 2014-8-6
 * */
public class ExcelUtil {

    /**
     * 创建excel文档,
     * [@param](http://my.oschina.net/u/2303379) list 数据
     * @param keys list中map的key数组集合
     * @param columnNames excel的列名
     * */
    public static Workbook createWorkBook(List> list, String []keys, String columnNames[]) {
        // 创建excel工作簿
        Workbook wb = new HSSFWorkbook();
        // 创建第一个sheet(页),并命名
        Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
        // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
        for(int i=0;i


差不多就是这样啦,你要是直接把代码拷过去肯定会报错啦,因为你没有我的实体类,在你找到我的代码之前肯定知道excel的操作啦,那这些你应该也能看懂,要是不知道,建议还是先看看excel的操作吧。



你可能感兴趣的:(Springmvc 生成并且下载文件--直接在浏览器下载。)