java导出Excel并下载

来源:互联网 发布:mac软件市场 编辑:程序博客网 时间:2024/06/05 22:20

前端访问后台,一开始失败,后来百度参考的这个 https://yq.aliyun.com/articles/8005

<a href="javascript:void(0)" class="easyui-linkbutton" id="btnExport" iconcls="icon-redo" onclick="showExport()">导出数据</a>


 //导出数据    function showExport(){    var tempIds = $('#pageList').datagrid('getSelections');    var ids = [];    $.each(tempIds,function(i,n){    ids.push(n.id);    });$.messager.confirm('确认', '确认把该搜索结果导出Excel表格 ?', function(r) {if (r) {if(ids.length>0){location.href="${ctx}/total/exportSelectedData?ids="+ids;}else{location.href="${ctx}/total/exportData";}}});     }


@RequestMapping("exportSelectedData")public void exportSelectedData(HttpServletRequest request,HttpServletResponse response){String tempIds = request.getParameter("ids");if(tempIds.contains(",")){ String [] ids = tempIds.split(","); this.export(ids,response);}else{ String [] ids = new String[1]; ids[0] = tempIds; this.export(ids,response);}}@RequestMapping("exportData")public void exportData(HttpServletResponse response){this.export(null,response);}/** * 导出数据保存成Excel * @param ids * @param response  * @return * @throws Exception  */private void export(String ids[], HttpServletResponse response) {List<UtrCemsTotal> list= null;if(null == ids){list = utrCemsTotalManager.selectAll();}else{list = utrCemsTotalManager.selectByIds(ids);}    String fileName =new SimpleDateFormat("yyyyMMdd").format(new Date());        // 第一步,创建一个webbook,对应一个Excel文件          HSSFWorkbook wb = new HSSFWorkbook();          // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet          HSSFSheet sheet = wb.createSheet("记录");         // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short          HSSFRow row = sheet.createRow(0);                 HSSFFont font = wb.createFont();        font.setFontName("宋体"); //字体        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //宽度                // 第四步,创建单元格,并设置值表头 设置表头居中          HSSFCellStyle style = wb.createCellStyle();          style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);        style.setFont(font);          HSSFCell cell = row.createCell(0);           cell.setCellValue("表名");          cell.setCellStyle(style);          cell = row.createCell(1);          cell.setCellValue("发送时间");          cell.setCellStyle(style);          cell = row.createCell(2);          cell.setCellValue("类型");          cell.setCellStyle(style);         cell = row.createCell(3);          cell.setCellValue("数量");          cell.setCellStyle(style);          // 第五步,写入实体数据          for (int i = 0; i < list.size(); i++)          {              row = sheet.createRow((int) i + 1);              UtrCemsTotal total = (UtrCemsTotal) list.get(i);              // 第四步,创建单元格,并设置值               HSSFCell cell2 = row.createCell(0);            cell2.setCellStyle(style);            cell2.setCellValue(total.getTableName());                     cell2 = row.createCell(1);            cell2.setCellStyle(style);            cell2.setCellValue(total.getCreatetime());             cell2 = row.createCell(2);            cell2.setCellStyle(style);            cell2.setCellValue(total.getType());             cell2 = row.createCell(3);            cell2.setCellStyle(style);            cell2.setCellValue(total.getTotal());         }          //设置自动调整宽度        sheet.autoSizeColumn(0);        sheet.autoSizeColumn(1);        sheet.autoSizeColumn(2);        sheet.autoSizeColumn(3);        // 第六步,保存文件          BufferedInputStream bis = null;BufferedOutputStream bos = null;        try {ByteArrayOutputStream os = new ByteArrayOutputStream();wb.write(os);byte[] content = os.toByteArray();InputStream is = new ByteArrayInputStream(content);response.reset();response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "utf-8"));ServletOutputStream out = response.getOutputStream();bis = new BufferedInputStream(is);            bos = new BufferedOutputStream(out);            byte[] buff = new byte[2048];            int bytesRead;            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {                bos.write(buff, 0, bytesRead);            }} catch (Exception e) {log.error("=====export exception=====", e);}finally {            try {if(bis != null)    bis.close();if(bos != null)    bos.close();} catch (IOException e) {log.error("=====close flow exception=====", e);}        } }


0 0
原创粉丝点击