Java 实现导出Excel功能

来源:互联网 发布:211软件专业大学排名 编辑:程序博客网 时间:2024/06/06 15:50

眼见为实,直接上效果图:



首先导出吧,我在项目中是这样用的:

第一步,创建一个webbook,对应一个Excel文件 
第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
第四步,设置样式
第五步,设置导出数据
第六步,弹出下载框

我把每一步的方法都抽离出来了,以便于模块化,实现程序的解藕,方便重用,下面我把代码贴出来:

// 第一步,创建一个webbook,对应一个Excel文件  HSSFWorkbook wb = new HSSFWorkbook();  // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet   HSSFSheet sheet = wb.createSheet("渠道已签接口");  // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  HSSFRow row = sheet.createRow((int) 0); // 第四步,设置样式HSSFCellStyle style = setHeadStyle(row, wb, 500, 10, HSSFFont.BOLDWEIGHT_BOLD);// 第五步,设置导出数据Map<String, Object> dataMap = new HashMap<String, Object>();dataMap.put("interfaceList", signInterfaceList);setExportDate(dataMap, sheet, row, style, 5);// 第六步,弹出下载框popDownload(response, wb, filePath);

    /**     *     * @Description 设置样式     * @author        <p style="color:#8e8e8e;font-family:微软雅黑;font-size=16px;font-weight:bold;">Cloud</p>     * @date        <p style="color:#000;font-family:微软雅黑;font-size=16px;">2016-11-25下午3:06:34</p>     * @param row    行     * @param wb    表格     * @param height    高度     * @param fontSize    字体大小     * @param fontWeight    字体粗细     * @return     */    private HSSFCellStyle setHeadStyle(HSSFRow row, HSSFWorkbook wb, int height, int fontSize, short fontWeight){        //设置高度        row.setHeight((short) height);        //创建单元格,并设置值表头 设置表头居中          HSSFCellStyle style = wb.createCellStyle();          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中        //设置字体        HSSFFont font = wb.createFont();        font.setFontHeightInPoints((short) fontSize);//设置字体大小        font.setBoldweight(fontWeight);//粗体粗细        style.setFont(font);//选择需要用到的字体格式          return style;    }    /**     *     * @Description 设置导出数据     * @author        <p style="color:#8e8e8e;font-family:微软雅黑;font-size=16px;font-weight:bold;">Cloud</p>     * @date        <p style="color:#000;font-family:微软雅黑;font-size=16px;">2016-11-25下午3:44:41</p>     * @param dataMap    导出数据Map     * @param sheet        导出表格     * @param row        行     * @param style        样式     * @param exportType    导出类型     */    @SuppressWarnings("unchecked")    private void setExportDate(Map<String, Object> dataMap, HSSFSheet sheet, HSSFRow row, HSSFCellStyle style, Integer exportType){        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        if(exportType == 5){            List<InterfaceConcludeSign> signInterfaceList = (List<InterfaceConcludeSign>) dataMap.get("interfaceList");            //设置表格标题            String[] title = new String[]{"接口名称", "接口类别", "子接口", "父接口", "接口备注", "输入", "输出", "购买价格",                    "套餐", "企业名称", "企业对接人", "渠道人员", "产品模式", "范围", "更新频率", "类型", "细小分类", "公司代码",                    "变更信息", "测试地址", "调用地址", "测试范围", "合同开始时间", "合同结束时间", "添加时间", "备注"};            setHead(row, style, title);            int c = 0;            for (InterfaceConcludeSign i : signInterfaceList) {                c++;                row = sheet.createRow((int) c);                Date pactSttime = i.getPact_sttime();                Date pactEntime = i.getPact_entime();                Date addTime = i.getAdd_time();                //时间处理                String packSTimeStr = pactSttime != null ? Common.fromDateY(pactSttime) : "";                String packETimeStr = pactEntime != null ? Common.fromDateY(pactEntime) : "";                String addTimeStr = addTime != null ? Common.fromDateY(addTime) : "";                // 第四步,创建单元格,并设置值                  String[] dataArray = new String[]{i.getInterface_name(), i.getCatalog_name(), i.getSon_interface_name(), i.getParent_interface_name(),                        i.getInterface_remark(), i.getOut_parameter(), i.getPut_parameter(), i.getBuy_price(), i.getPack_name(), i.getCompany_name(),                        i.getCompany_abutment(), i.getChannel_user(), i.getProduct_model(), i.getScope(), i.getUpd_rate(), i.getType(), i.getTiny_catalog(),                        i.getCompany_code(), i.getUpd_info(), i.getTest_url(), i.getCell_url(), i.getTest_scope(), packSTimeStr, packETimeStr,                        addTimeStr, i.getRemark()};                for (int j = 0; j < dataArray.length; j++) {                    row.createCell(j).setCellValue(dataArray[j]);                    if(dataArray[j] != null && dataArray[j].length() > 0){                        sheet.setColumnWidth(j, dataArray[j].toString().length() * 712);                    }                }            }    /**     *     * @Description 弹出下载提示框     * @author        <p style="color:#8e8e8e;font-family:微软雅黑;font-size=16px;font-weight:bold;">Cloud</p>     * @date        <p style="color:#000;font-family:微软雅黑;font-size=16px;">2016-11-25下午1:25:51</p>     * @param response    请求头信息     * @param wb        表格     * @param filePath    文件路径     * @throws IOException     */    private void popDownload(HttpServletResponse response, HSSFWorkbook wb, String filePath) throws IOException{        //初始化流        ByteArrayOutputStream os = new ByteArrayOutputStream();        BufferedInputStream bis = null;        BufferedOutputStream bos = null;        try {            //表格定稿数据            wb.write(os);            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((filePath).getBytes(), "iso-8859-1"));            ServletOutputStream out = response.getOutputStream();            bis = new BufferedInputStream(is);            bos = new BufferedOutputStream(out);            byte[] buff = new byte[2048];            int bytesRead;            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {                bos.write(buff, 0, bytesRead);            }        } catch (Exception e) {            logger.info("文件下载失败");            e.printStackTrace();        } finally {            //关闭流            if (bis != null)                bis.close();            if (bos != null)                bos.close();            if (os != null)                os.close();        }    }



以上程序是我项目中用到的,直接复制出来可能没法使用,以上只是实现方式,欢迎交流:Q 294706865;

1 0
原创粉丝点击