利用Poi导出Excel

在实际的项目开发中,经常会遇到将Web页面中的数据,如:表格、后台数据等导出为Excel的功能操作。那么就可以使用Poi来操作Excel。可以通过代码控制Excel的显示内容、样式等。因为Poi操作样式的一系列的方法,基本都是针对单元格来说,所以,若Excel中单元格的样式有很大的区别,那么用Poi显然是十分不合适,要写一大堆重复的样式代码。有一个变通法:就是可以把Excel的样式先做好,相当于一个模板,那么操作Excel时,就可以只填充数据啦。

poi导出Excel的基础实现:
后台代码:

// 第一步,创建一个webbook,对应一个Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet("好朋友");
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制  
        HSSFRow row = sheet.createRow(0);
        // 第四步,创建单元格,并设置值表头 设置表头居中  
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("盖伦");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("剑圣");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("锤石");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("寒冰");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("狮子狗");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("瑞文");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("EZ");
        cell.setCellStyle(style);

        cell = row.createCell(7);
        cell.setCellValue("德莱文");
        cell.setCellStyle(style);

        cell = row.createCell(8);
        cell.setCellValue("人马");
        cell.setCellStyle(style);
        cell = row.createCell(9);
        cell.setCellValue("石头人");
        cell.setCellStyle(style);
        cell = row.createCell(10);
        cell.setCellValue("兰博");
        cell.setCellStyle(style);
        //上面创建了一行10列


    response.setContentType("text/html;charset=UTF-8");
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + new String(("我的朋友们.xls").getBytes("utf-8"), "ISO-8859-1")); //文件名编码
            stream = response.getOutputStream();
            wb.write(stream); //写入reponse中

前台的代码:

window.location.href = "${root.contextPath!}/export/exportedata    //后台方法的路径。这里是Springmvc.

注意:前台是不能用ajax请求的。Ajax没法支持下载,它只能用于文档或数据的处理。需提供一个窗口进行下载。下面这样是不可以的

$.ajax({
        url : '${root.contextPath!}/export/exportedata,
        type : 'post',
        async : false,
        success : function(data) {

        },
        error : function() {
        }
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值