ExtJS實現Excel導出

ExtJS是一種基於客戶端開發的AJAX應用,是一個與後臺技術無關的前臺ajax框架。由於項目需求,我們需要實現Excel的導出功能,前臺界面是用ExtJS實現。如何實現呢?


1. 使用POI組件實現excel導出功能

//獲取問題列表
List<Suggestion> targetStockList = suggestionService.getSuggestionList(map);
 
		//創建一個新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		//創建sheet頁
		HSSFSheet sheet = workBook.createSheet();
		//sheet頁名稱
		workBook.setSheetName(0, "targetStockList");
		//創建header頁
		HSSFHeader header = sheet.getHeader();
		//設置標題居中
		header.setCenter("標題");
		
		//設置第一行爲Header
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell0 = row.createCell(Short.valueOf("0"));
		HSSFCell cell1 = row.createCell(Short.valueOf("1"));
		HSSFCell cell2 = row.createCell(Short.valueOf("2"));
 
		
		// 設置字符集
		cell0.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
		cell2.setEncoding(HSSFCell.ENCODING_UTF_16);

		
		cell0.setCellValue("問題標題");
		cell1.setCellValue("問題描述");
		cell2.setCellValue("反饋時間");
	
		
		if(targetStockList != null && !targetStockList.isEmpty()) {
			for(int i = 0; i < targetStockList.size(); i++) {
				Suggestion targetStock = targetStockList.get(i);
				row = sheet.createRow(i + 1);
				cell0 = row.createCell(Short.valueOf("0"));
				cell1 = row.createCell(Short.valueOf("1"));
				cell2 = row.createCell(Short.valueOf("2"));

				
				// 設置字符集
				cell0.setEncoding(HSSFCell.ENCODING_UTF_16);
				cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
				cell2.setEncoding(HSSFCell.ENCODING_UTF_16);

				
				cell0.setCellValue(targetStock.getType());
				cell1.setCellValue(targetStock.getContent());
				cell2.setCellValue(targetStock.getPublishTime());
	 
 
				
				sheet.setColumnWidth((short) 0, (short) 4000);
				sheet.setColumnWidth((short) 1, (short) 4000);
				sheet.setColumnWidth((short) 2, (short) 4000);
			}
		}
		
		//通過Response把數據以Excel格式保存
		response.reset();
		response.setContentType("application/msexcel;charset=UTF-8");
		try {
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ new String(("用戶意見信息表" + ".xls").getBytes("GBK"),
							"ISO8859_1") + "\"");
			OutputStream out = response.getOutputStream();
			workBook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

2.ExtJS調用此函數,實現Excel的導出

我們知道在界面上通過一個按鈕實現Excel的導出,ExtJS的按鈕一般都是通過Ext.Ajax.request的異步請求實現數據提交的。但是在這裏我們不能使用異步調用,我們需要在直接提示給用戶是否保存或打開此文檔。如何實現呢?

       其實很簡單,我們如果瞭解了ExtJS就是Javascript開發的,我們就能夠很容易實現此功能了。我們在按鈕的觸發事件中寫入此段代碼就能實現Excel的函數調用了。

	// 初始化 Excel導出 的按鈕
	var exportExcel = Ext.get('exportExcel');
	exportExcel.on('click', exportButtonClick);
	
	function exportButtonClick (){
		 window.location.href = Ext.CONTEXT + '/admin/suggestion.do?method=exportTargetList';
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章