poi 制作 excel 並且以文件流的方式 傳輸到客戶端下載


最近做了poi模塊,總結一下。

poi是常用的報表導出工具,一般業務需求基本都可以滿足,我們第一步導入基本的jar包,這里導入的是3.10的版本,不是最新的。

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.10-FINAL</version>
        </dependency>

然后基本的導出代碼如下:

    public HSSFWorkbook export() throws Exception {
        // 創建新工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle cellStyle = titlStyle(workbook);
        //bigdataip=192.168.100.104, qxname=wwwwwww, port=9595, totalNum=210217
        // 創建表頭以及字段名稱
        HSSFSheet sheet = workbook.createSheet(name);
        sheet.setColumnWidth(0, 256*15); 
        sheet.setColumnWidth(1, 256*30); 
        sheet.setColumnWidth(2, 256*18); 
        sheet.setColumnWidth(3, 256*18); 
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 10));
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue( "");
        cell.setCellStyle(cellStyle);
        
        HSSFCellStyle cellStyleNei = workbook.createCellStyle();
        // 新建font實體
        HSSFFont hssfFontNei = workbook.createFont();
        // 字體大小
        hssfFontNei.setFontHeightInPoints((short) 14);
        hssfFontNei.setFontName("宋體");
        // 粗體
        hssfFontNei.setBoldweight(Font.BOLDWEIGHT_BOLD);
        
        cellStyleNei.setFont(hssfFontNei);
        
        
        HSSFRow row1 = sheet.createRow(1);
        HSSFCell cell1 = row1.createCell(0);
        cell1.setCellValue("xxx");
        cell1.setCellStyle(cellStyleNei);
        HSSFCell cell2 = row1.createCell(1);
        cell2.setCellValue("xxx");
        cell2.setCellStyle(cellStyleNei);
        HSSFCell cell3 = row1.createCell(2);
        cell3.setCellValue("xxx");
        cell3.setCellStyle(cellStyleNei);
        HSSFCell cell4 = row1.createCell(3);
        cell4.setCellValue("xxx");
        cell4.setCellStyle(cellStyleNei);
        
        HSSFCellStyle cellStyleNeiR = workbook.createCellStyle();
        // 新建font實體
        HSSFFont hssfFontNeiR = workbook.createFont();
        // 字體大小
        hssfFontNeiR.setFontHeightInPoints((short) 12);
        hssfFontNeiR.setFontName("宋體");
        // 粗體
        hssfFontNeiR.setBoldweight(Font.BOLDWEIGHT_BOLD);
        
        cellStyleNeiR.setFont(hssfFontNeiR);
        
        for(int i =0 ;i<dataList.size();i++) {
            HSSFRow rowf = sheet.createRow(i+2);
            HSSFCell cellf1 = rowf.createCell(0);
            cellf1.setCellValue(dataList.get(i).get("key值"));
            cellf1.setCellStyle(cellStyleNeiR);
            HSSFCell cellf2 = rowf.createCell(1);
            cellf2.setCellValue(dataList.get(i).get("key值"));
            cellf2.setCellStyle(cellStyleNeiR);
            HSSFCell cellf3 = rowf.createCell(2);
            cellf3.setCellValue(dataList.get(i).get("key值"));
            cellf3.setCellStyle(cellStyleNeiR);
            HSSFCell cellf4 = rowf.createCell(3);
            cellf4.setCellValue(dataList.get(i).get("key值"));
            cellf4.setCellStyle(cellStyleNeiR);
        }
    

        // 輸出到磁盤中 放開這段代碼可以直接將excel導出到桌面
        /*String ip_yh = tools.getIpAddress(request);
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com=fsv.getHomeDirectory(); 
        String cdopt = com.getPath();
        cdopt =cdopt.replaceAll("\\\\","/");
        File file = new File(cdopt +"/"+ name +ip_yh+ "數據統計.xls" );
        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();*/
        return workbook ;

    }

然后我們寫servlet:

@RequestMapping(value = "/cprint")
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response) {
      
        poiExcle poiexcle = new poiExcle();
        try {
            wb = poiexcle.export();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            String fileName = "數據統計.xls";
           

            response.setContentType("application/octet-stream");
            response.setHeader("name", fileName);
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition",
                    "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");

            wb.write(response.getOutputStream()); // 輸出流控制workbook

            response.getOutputStream().flush();

            response.getOutputStream().close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

最主要的代碼就是這一段:

  response.setContentType("application/octet-stream");
            response.setHeader("name", fileName);
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-disposition",
                    "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");

            wb.write(response.getOutputStream()); // 輸出流控制workbook

            response.getOutputStream().flush();

            response.getOutputStream().close();

將  HSSFWorkbook 對象寫到 response里的輸出流,一定要記得將 filename 設置一下編碼,不然會顯示 ____.xls

ps.剛實習,時間不太夠,先這樣簡單記錄一下,后面慢慢整理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM