Java 實現匯出Excel功能__Java

來源:互聯網
上載者:User

眼見為實,直接上效果圖:



首先匯出吧,我在項目中是這樣用的:

第一步,建立一個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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.