导出Excel表 1.jsp页面传出要导出信息ID <body> <form action="outexcel" method="post"> <input type="checkbox" name="id" value="1" checked="checked"/>11111111 <br> <input type="checkbox" name="id" value="2"/>22222222 <br> <input type="submit" value="导出表"/> </form> </body> 2.servlet处理 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] id = request.getParameterValues("id"); if (id != null || id.length != 0) { Select slt = new Select(); List lst = slt.slt(id); OutputStream os = null; WritableWorkbook wwb = null; try { os = new FileOutputStream("filename.xls"); wwb = Workbook.createWorkbook(os); Iterator it = lst.iterator(); Output op = new Output(it,wwb); op.doConfigExcel(); } catch (Exception e) { } finally { try { wwb.write(); wwb.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } } } else { response.sendRedirect("downexcel.jsp"); return; } response.setHeader("Content-disposition", "attachment;filename=filename"); response.setContentType("application/msexcel"); try { FileInputStream fileInputStream = new FileInputStream("filename.xls"); OutputStream out = response.getOutputStream(); int i = 0; while ((i = fileInputStream.read()) != -1) { out.write(i); } fileInputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 3.sql操作类,查找记录,返回list public class Select { IDataConfig dc = null; public List slt(String[] id){ dc = new DataConfig(); List lst = new ArrayList(); try { dc.openConnection(); ResultSet rs = null; for(int i=0;i<id.length;i++){ String sql = "select * from test where id=" + id[i]; rs = dc.executeQuery(sql); rs.next(); Bean bn = new Bean(); bn.setId(rs.getInt(1)); bn.setName(rs.getString(2)); bn.setDate(rs.getDate(3)); lst.add(bn); } } catch (SQLException ex) { Logger.getLogger(Select.class.getName()).log(Level.SEVERE, null, ex); } return lst; } 4.生成Excel的操作类 public class Output { private Iterator it = null; private WritableWorkbook wwb = null; public Output(Iterator it, WritableWorkbook wwb) { this.it = it; this.wwb = wwb; } public void setIt(Iterator it) { this.it = it; } public void setWwb(WritableWorkbook wwb) { this.wwb = wwb; } public void doConfigExcel() { WritableSheet sheet = wwb.createSheet("导出表test", 0); Label v = null; try { Label ID = new Label(0, 0, "ID"); sheet.addCell(ID); Label name = new Label(1, 0, "姓名"); sheet.addCell(name); Label date = new Label(2, 0, "时间"); sheet.addCell(date); int i = 0; while (it.hasNext()) { i++; Bean bn = (Bean)it.next(); Label idv = new Label(0,i,String.valueOf(bn.getId())); sheet.addCell(idv); Label namev = new Label(1,i,bn.getName()); sheet.addCell(namev); Label datev = new Label(2,i,bn.getDate()); sheet.addCell(datev);} } catch (WriteException ex) { Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex); } } } Date只是String类型,test嘛,小懒了一下!