標籤:http java 使用 os io 資料 for ar
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‘;};