使用poi須要用到的jar包web
本文的導出基於execl的模板導出,在大部分表頭固定而格式花樣比較複雜的建議使用本文介紹的方法(表頭固定,只須要填充值)apache
一、在webroot目錄下新建report文件夾來存放模板execl文件app
二、jsp前臺請求對應的action代碼jsp
String path = request.getSession().getServletContext().getRealPath("/")+"report/goodslaunch.xls"; String id = request.getParameter("id");//須要導出的數據的某Id String name = this.xxService.loadNameById(id);//查詢出id對應的真實名稱 ByteArrayOutputStream os = (ByteArrayOutputStream)this.xxxService.expExecl(id, path); if(null!=os && os.size()>0){ byte[] buffer = os.toByteArray(); String fileName = "[" + name + "]XX模塊." + path.substring(path.lastIndexOf(".")+1, path.length()); // 設置response的Header response.setContentType("application/x-msdownload; charset=UTF-8"); response.addHeader("content-type", "application/x-msexcel"); response.addHeader("content-disposition", "attachment; filename="+ new String(fileName.getBytes("gb2312"), "iso8859-1")); //這裏必須轉碼,或者會有問題 response.setContentLength(buffer.length); OutputStream out = response.getOutputStream(); out.write(buffer); out.flush(); os.close(); }
三、service代碼this
import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; /** * 導出生成execl * @throws Exception */ public OutputStream expExecl(String id,String execlPath) throws Exception{ List<XxDto> data = this.getSearchResult(id); Workbook wb = WorkbookFactory.create(new File(execlPath)); Font font = wb.createFont(); font.setFontName("微軟雅黑"); font.setFontHeightInPoints((short) 10); CellStyle style = wb.createCellStyle(); style.setBorderBottom((short)1); style.setBorderLeft((short)1); style.setBorderRight((short)1); style.setBorderTop((short)1); style.setFont(font); if(data.size()>0){ Sheet sheet = wb.getSheetAt(0); int rownum = 1; for(XxDto item : data){ Row row = sheet.createRow(rownum++); int cellnum = 0; row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); row.createCell(cellnum++).setCellValue(item.getXxx()); //設置樣式 for(int i=0; i<cellnum; i++){ row.getCell(i).setCellStyle(style); } } } OutputStream os = new ByteArrayOutputStream(); wb.write(os); return os; }
當沒有模板時須要建立文件(2007和2007之前的execl的寫法是不一樣的)spa
Workbook wb;
Sheet sheet;excel
File file = new File(fileName); //文件不存在 if(!file.exists()){ addFlag = false; } if(!addFlag){ if("xls".equals(fileSuffix)){ //老execl wb = new HSSFWorkbook(); }else{ //新execl wb = new XSSFWorkbook(); } sheet = wb.createSheet("data"); createExeclHead(sheet); }else{ //利用工廠讀取execl能夠不須要關心execl的版本問題 wb = WorkbookFactory.create(file); sheet = wb.getSheetAt(0); }
更詳細的用法能夠去官網看文檔:http://poi.apache.org/code