使用poi导出execl
使用poi需要用到的jar包
本文的导出基于execl的模板导出,在大部分表头固定而格式花样比较复杂的建议使用本文介绍的方法(表头固定,只需要填充值)
1、在webroot目录下新建report文件夹来存放模板execl文件
2、jsp前台请求对应的action代码
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(); }
3、service代码
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的写法是不同的)
Workbook wb;
Sheet sheet;
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/