最近做grid列表相关数据导出到excel功能,根据自己选择的列导出成excel 并且下载到本地。下载位置根据配置文件进行的配置。废话不说 直接上关键代码:
需要引入相关的包:
compile ‘net.sourceforge.jexcelapi:jxl:2.6.12‘这是我项目中gradle的配置。
@Override public void exportExcel(Integer[] ids,HttpServletResponse response) { List<WithdrawDeposit> listMsg = new ArrayList<>(); WithdrawDeposit withdrawDeposit; for (Integer id : ids) { withdrawDeposit = settlementDao.getSettlementInfo(id); listMsg.add(withdrawDeposit); } SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String dirPath = ImgUploadUtil.EXCEL_DIR;//导出到磁盘的位置 配置文件的配置 String fileName = new Date().getTime() + ".xls";//生成的excel文件名 File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } dirPath = dirPath + "/" + fileName;//文件路径 try { //*.xls为要新建的文件名 WritableWorkbook book = Workbook.createWorkbook(new File(dirPath)); //生成名为“***”的工作表,参数0表示这是第一页 WritableSheet ws = book.createSheet("结算申请记录", 0); // 写表头 jxl.write.Label label1 = new jxl.write.Label(0, 0, "申请号"); jxl.write.Label label2 = new jxl.write.Label(1, 0, "提现金额"); jxl.write.Label label3 = new jxl.write.Label(2, 0, "申请时间"); jxl.write.Label label4 = new jxl.write.Label(3, 0, "支付类型"); jxl.write.Label label5 = new jxl.write.Label(4, 0, "账号"); jxl.write.Label label6 = new jxl.write.Label(5, 0, "状态"); ws.addCell(label1);// 放入工作簿 ws.addCell(label2); ws.addCell(label3); ws.addCell(label4); ws.addCell(label5); ws.addCell(label6); for (int i = 0; i < listMsg.size(); i++) { label1 = new jxl.write.Label(0, i + 1, listMsg.get(i).getApplicationNo());// 建立第一列 label2 = new jxl.write.Label(1, i + 1, listMsg.get(i).getAmount().toString().trim());// 建立第二列 label3 = new jxl.write.Label(2, i + 1, format.format(listMsg.get(i).getOpTime()));// 建立第三列 label4 = new jxl.write.Label(3, i + 1, listMsg.get(i).getPayType());// 建立第四列 label5 = new jxl.write.Label(4, i + 1, listMsg.get(i).getAccountNo());// 建立第五列 label6 = new jxl.write.Label(5, i + 1, listMsg.get(i).getStatus());// 建立第六列 // 放入工作簿 ws.addCell(label1); ws.addCell(label2); ws.addCell(label3); ws.addCell(label4); ws.addCell(label5); ws.addCell(label6); } //写入数据 book.write(); //关闭文件 book.close(); System.out.println("导出成功!!!!!!!!"); // 下载到本地 ServletOutputStream out = response.getOutputStream(); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1")); byte[] bytes = new byte[0xffff]; InputStream is = new FileInputStream(new File(dirPath)); int b; while ((b = is.read(bytes, 0, 0xffff)) > 0) { out.write(bytes, 0, b); } is.close(); out.flush(); } catch (Exception e) { e.printStackTrace(); } }
执行之后会在你本地电脑的磁盘下获取你导出的文件。
时间: 2024-10-27 09:31:02