1. 程式人生 > >java實現下載excle(jxl和poi 兩種方式)

java實現下載excle(jxl和poi 兩種方式)

@RequestMapping(value="/download_index")
	public  String  downloadExcel(HttpServletRequest request,HttpServletResponse response,String name) {

		OutputStream os =  null;
    	WritableWorkbook wbook = null;
    	try {
    		
            String flieName =  name;
            // 取得輸出流
            os = response.getOutputStream();
            response.reset();// 清空輸出流
            // 設定輸出檔案頭
            response.setHeader("Content-disposition", "attachment; filename=" + new String(flieName.getBytes("UTF-8"), "ISO8859-1") + ".xls");
            // 定義輸出型別
            response.setContentType("application/msexcel;charset=utf-8");
            
            // 建立excel檔案
            wbook = Workbook.createWorkbook(os);
            
            //要下載的list資料
            List<UnifiedVO>  unifiedVOList = new ArrayList<UnifiedVO>();
            	
            // 設定資料
            setWorkBookData(unifiedVOList, wbook,flieName);
            
            if (wbook.getNumberOfSheets() > 0) {
                wbook.write();
            }
            wbook.close();
            os.close();
            
        } catch (Exception e) {
        	e.printStackTrace();
        }finally {
		if(wbook != null) {
				 try {
					wbook.close();
				} catch (WriteException | IOException e) {
					e.printStackTrace();
				}
			}
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		}
		return null;
	}

String [] codes  是頁面傳過來的要查詢的內容,name 是傳過來動態表名。for迴圈查出List資料,然後統一用unifiedVOList.addAll()合在一起。然後將list資料集合傳入方法內、work、表名傳入方法內。

	private void setWorkBookData(List<UnifiedVO> giftRecords, WritableWorkbook wbook,String name)
			throws WriteException, RowsExceededException {
		
		final Integer EXCEL_MAX_NUMBER = 65535;
		
        WritableCellFormat wc = new WritableCellFormat();
        // 設定居中
        wc.setAlignment(Alignment.CENTRE);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		WritableSheet wsheet = null;

		int sheetNumber = 0;
		if (giftRecords.size() % EXCEL_MAX_NUMBER != 0) {
		    sheetNumber = giftRecords.size() / EXCEL_MAX_NUMBER + 1;
		} else {
		    sheetNumber = giftRecords.size() / EXCEL_MAX_NUMBER;
		}

		for (int j = 0; j < sheetNumber; j++) {
		    wsheet = wbook.createSheet(name + (j + 1), j); // sheet名稱
		    // 開始生成主體內容
		    wsheet.addCell(new Label(0, 0, "名稱", wc));
		    wsheet.setColumnView(0, 32);
		    
		    wsheet.addCell(new Label(1, 0, "時間", wc));
		    wsheet.setColumnView(1, 20);

		    wsheet.addCell(new Label(2, 0, "資料", wc));
		    wsheet.setColumnView(2, 32);

		    wsheet.addCell(new Label(3, 0, "單位", wc));
		    wsheet.setColumnView(3, 30);

		    int start = EXCEL_MAX_NUMBER * j;
		    int end = EXCEL_MAX_NUMBER + start;

		    for (int i = start, k = giftRecords.size(); i < k && i < end; i++) {
		    	UnifiedVO unifiedVO = giftRecords.get(i);
		        int row = i - start + 1;
		        wsheet.addCell(new Label(0, row, unifiedVO .getKey(), wc));
		        wsheet.addCell(new Label(1, row, unifiedVO .getDate(), wc));
		        wsheet.addCell(new Label(2, row, unifiedVO .getData(), wc));
		        wsheet.addCell(new Label(3, row, unifiedVO .getUnit(), wc));
		    }
		}
	}

wsheet.addCell(new Label(0, 0, "名稱", wc))
wsheet.addCell(new Label(1, 0, "時間", wc));
wsheet.addCell(new Label(2, 0, "資料", wc));

wsheet.addCell(new Label(3, 0, "單位", wc));

上面的欄位一一對應VO欄位

wsheet.addCell(new Label(0, row, unifiedVO .getKey(), wc));
wsheet.addCell(new Label(1, row, unifiedVO .getDate(), wc));
wsheet.addCell(new Label(2, row, unifiedVO .getData(), wc));
wsheet.addCell(new Label(3, row, unifiedVO .getUnit(), wc));

對應的maven API :

		<!-- 匯出excel jxl  -->
		<dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>

=====================================================================================

 poi 匯出:

	<!-- 匯出excel poi  -->
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi</artifactId>
		    <version>3.17</version>
		</dependency>
        

最簡單的下載資料實現:

public test(HttpServletRequest request,HttpServletResponse response) {
		
		List<?> arrayList  = new ArrayList<Object>();
		
		OutputStream os =  null;
		
        // 取得輸出流
        try {
			os = response.getOutputStream();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
        response.reset();// 清空輸出流
        
        //1.在記憶體中建立一個excel檔案
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        //2.建立工作簿
        HSSFSheet sheet = hssfWorkbook.createSheet();
        
        //3.建立標題行
        HSSFRow titlerRow = sheet.createRow(0);
        HSSFCellStyle createCellStyle = hssfWorkbook.createCellStyle();//建立單元格樣式 
        
        createCellStyle.setFillForegroundColor((short) 255);// 設定背景色
        createCellStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION); // 居中
        createCellStyle.setBorderTop(BorderStyle.SLANTED_DASH_DOT);
        
        titlerRow.createCell(0).setCellValue("營銷顧問");
     
       
        titlerRow.setRowStyle(createCellStyle);
        
        for (Object o : arrayList) {
        	  //獲取最後一行的行號
            int lastRowNum = sheet.getLastRowNum();
            
            HSSFRow dataRow = sheet.createRow(lastRowNum + 1);
            
            dataRow.createCell(0).setCellValue(o.get營銷顧問());
       
		}
        //5.建立檔名
        String fileName = "區域資料統計.xls";
        //9.設定資訊頭
        response.setContentType(fileName);
        try {
			fileName = new String (fileName.getBytes ("utf-8"),"ISO8859-1");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        //10.寫出檔案,關閉流
        try {
			hssfWorkbook.write(os);
		} catch (IOException e1) {
		}
        try {
			hssfWorkbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}