spring MVC 生成并下载Excel

2 篇文章 0 订阅
1 篇文章 0 订阅

1、Controller类:

@Controller
@RequestMapping("down")
public class down {
    @RequestMapping(params = "downExcel")
    public String download(HttpServletRequest request,HttpServletResponse response) throws IOException{
    String columnNames[]={"ID","项目名","销售人","负责人","所用技术","备注"};//列名
    //生成一个Excel文件
    // 创建excel工作簿
    Workbook wb = new HSSFWorkbook();
    // 创建第一个sheet(页),并命名
    Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
    // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
    for(int i=0;i<keys.length;i++){
        sheet.setColumnWidth((short) i, (short) (35.7 * 150));
    }
    // 创建第一行
    Row row = sheet.createRow((short) 0);
    //设置列名
    for(int i=0;i<columnNames.length;i++){
        Cell cell = row.createCell(i);
        cell.setCellValue(columnNames[i]);
    }
    //同理可以设置数据行
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        wb.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;
    }
}

前台代码:

<input type="button" value="导出数据" onclick="download()"/>

//js代码
function download(){
    var url="down.do?downExcel";
    window.open(url);
}

文章参考:http://my.oschina.net/aptx4869/blog/298507

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值