需求:在界面上選擇一個日期,然后點擊導出按鈕,直接導出選擇月份的考勤excel文件.
這篇文章主要是介紹如何下載文件!
jsp中代碼:
<div class="form-group"> <label class="col-md-1 col-sm-1 control-label manage-lab">當前月份:</label> <div class="col-md-2 col-sm-2 manage-wid manage-fat"> <input type="text" class="form-control" name="" id="selectMonth" readonly="readonly" onclick="WdatePicker({dateFmt: 'yyyy-MM', el:'selectMonth'})" placeholder="請選擇日期" onchange="selectMonth_onchange()" > </div> <button class="btn manage-btn col-md-1 check-search" type="button" onclick="refreshAttendanceList()"> 查詢 </button> <input type="file" name="fileSelectName" id="fileSelect" onchange="uploadAction()" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;"/> <button class="btn manage-btn att-check-btn check-search" style="width: 130px;" type="button" onclick="importAction()"> 導入打卡記錄 </button> <!-- 假裝點擊 --> <a id="export_a_id" href="${ctx}/oa/attendance/export.do?dateStirng=2015-12-21" > <button class="btn manage-btn att-check-btn check-search" style="width: 130px;" type="button"> 導出考勤 </button> </a> </div>
點擊按鈕的時候實際上是通過點擊 <a href 去實現的.
在日期選擇框中添加了onchange()事件
js代碼:
/** * 日期選擇變化的時候,更新a標簽里的超鏈接地址 * @returns */ function selectMonth_onchange() { var dateString = $("#selectMonth").val(); var url = yyoa_context + '/oa/attendance/export.do?dateString=' + dateString; var export_a = $("#export_a_id"); export_a.attr("href", url); }
export.do 的 controller層代碼, 目前這里只能用get方式,不能用post 方式.
@ResponseBody @RequestMapping(value = "/export", method = RequestMethod.GET) public void export(String dateString, HttpServletRequest request, HttpServletResponse response) { try { Date date = null; if (dateString.length() == 0) { date = new Date(); } else if (dateString.length() < 10) { dateString += "-01"; date = DateUtil.str2Date(dateString, DateUtil.DEFAULT_DATE_FORMAT); } String tmpDateString = DateUtil.date2Str(date, "yyyy-MM"); String fileName = tmpDateString + "-records" + ".xls"; String filePath = this.getClass().getClassLoader().getResource("tmp").getPath() + fileName; // 獲取考勤數據 List<AttendanceExtend> attendanceExtends = this.attendanceService.selectAttendanceByDate(date); // 得到excel對象 HSSFWorkbook workbook = this.attendanceService.setExportExcelTemplate(attendanceExtends); // 寫文件到服務器路徑 FileOutputStream out = new FileOutputStream(filePath); workbook.write(out); out.flush(); out.close(); // 下載文件 response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); InputStream inputStream = new FileInputStream(new File(filePath)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } os.close(); inputStream.close(); } catch (Exception exception) { } }
這樣就可以直接下載了.