需求:在界面上选择一个日期,然后点击导出按钮,直接导出选择月份的考勤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; 0;height: 0;"/> <button class="btn manage-btn att-check-btn check-search" style=" 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=" 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) { } }
这样就可以直接下载了.