1. 使用POI組件實現excel導出功能java
//獲取問題列表
app
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
// 初始化 Excel導出 的按鈕
code
var exportExcel = Ext.get('exportExcel'); exportExcel.on('click', exportButtonClick); function exportButtonClick (){ window.location.href = Ext.CONTEXT + '/admin/suggestion.do?method=exportTargetList'; };