前台代碼:
function exportReport(){var url = "后台處理方法地址"; download(url); } function download(url){ Ext.Msg.wait("正在下載數據,請稍等。。。"); if (!Ext.fly('downForm')){ //如果不存在一個id為"downForm"的form表單,則執行下面的操作 //下面代碼是在創建一個表單以及添加相應的一些屬性 var downForm = document.createElement('form'); //創建一個form表單 downForm .id = 'downForm'; //該表單的id為downForm downForm .name = 'downForm'; //該表單的name屬性為downForm downForm .className = 'x-hidden'; //該表單為隱藏的 downForm .action = url; downForm .method = 'post'; //表單的提交方法 document.body.appendChild(downForm ); //講form表單追加到body里面 } Ext.fly('downForm').dom.submit(); //調用form表單的submit方法,提交表單,從而開始下載文件 //如果存在id為downForm的表單,則將它移除掉 if (Ext.fly('downForm')){ document.body.removeChild(downForm ); } Ext.Msg.hide(); }
后台代碼:
@RequestMapping(value="/exportExcel",method = {RequestMethod.POST,RequestMethod.GET},produces = "text/html; charset=UTF-8") public static void exportExcel(HttpServletRequest request, HttpServletResponse response) { response.addHeader("Content-Disposition", "attachment;filename=exportInfo.xlsx"); response.setContentType("application/octet-stream");try { //獲取需要下載的文件
File output = null;
InputStream in = new FileInputStream(output); // 獲取下載文件的輸入流
int count = 0;
byte[] by = new byte[1024];
// 通過response對象獲取OutputStream流
OutputStream out = response.getOutputStream();
while ((count = in.read(by)) != -1) {
out.write(by, 0, count);// 將緩沖區的數據輸出到瀏覽器
}
in.close();
out.flush();
out.close();
} catch (Exception e) { e.printStackTrace(); } }