JavaWeb導出Excel文件并彈出下載框
一、引言
在Java Web開發(fā)中經(jīng)常涉及到報表,最近做的項目中需要實現(xiàn)將數(shù)據(jù)庫中的數(shù)據(jù)顯示為表格,并且實現(xiàn)導出為Excel文件的功能。
二、相關jar包
使用POI可以很好的解決Excel的導入和導出的問題,POI下載地址:
poi-3.6-20091214.jar
三、關鍵代碼
首先導入上述jar包。
在生成excel時一般數(shù)據(jù)源形式為一個List,下面把生成Excel格式的代碼貼出來:
/** * 以下為生成Excel操作 */ // 1.創(chuàng)建一個workbook,對應一個Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 2.在workbook中添加一個sheet,對應Excel中的一個sheet HSSFSheet sheet = wb.createSheet("XXX表"); // 3.在sheet中添加表頭第0行,老版本poi對excel行數(shù)列數(shù)有限制short HSSFRow row = sheet.createRow((int) 0); // 4.創(chuàng)建單元格,設置值表頭,設置表頭居中 HSSFCellStyle style = wb.createCellStyle(); // 居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 設置表頭 HSSFCell cell = row.createCell(0); cell.setCellValue("表頭1"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("表頭2"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("表頭3"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("表頭4"); cell.setCellStyle(style); cell = row.createCell(4); cell.setCellValue("表頭5"); cell.setCellStyle(style);
生成excel格式后要將數(shù)據(jù)寫入excel:
// 循環(huán)將數(shù)據(jù)寫入Excel for (int i = 0; i < lists.size(); i++) { row = sheet.createRow((int) i + 1); List list= lists.get(i); // 創(chuàng)建單元格,設置值 row.createCell(0).setCellValue(list.getXXX()); row.createCell(1).setCellValue(list.getXXX()); row.createCell(2).setCellValue(list.getXXX()); row.createCell(3).setCellValue(list.getXXX()); row.createCell(4).setCellValue(list.getXXX()); }
之后將生成的Excel以流輸出。
*不彈出下載框
FileOutputStream out =new FileOutputStream("E:/XXX.xls"); wb.write(out); out.close();
*彈出下載框
String fileName = "XXX表"; ByteArrayOutputStream os = new ByteArrayOutputStream(); wb.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設置response參數(shù),可以打開下載頁面 res.reset(); res.setContentType("application/vnd.ms-excel;charset=utf-8"); res.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = res.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); }
完成以上操作之后即可跳轉到其他頁面。
同時POI還可以將Excel上傳解析顯示在網(wǎng)頁中,這個另一篇文章總結,敬請期待!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。